In react
const allInputs = { imgUrl: '' };
const [imageAsFile, setImageAsFile] = useState('');
const [imageAsUrl, setImageAsUrl] = useState(allInputs);
const [media, setMedia] = useState(null);
const handleImageAsFile = (e) => {
const image = e.target.files[0]
setImageAsFile(imageFile => (image));
console.log(imageAsFile);
}
Here is the input code, when I click this button, all types of files show, but I want to be able to store the type of file it is in a variable
<input type="text"
id="phone"
onChange={(e) => setPhone(e.target.value)}
/>
For example, if I select an image, how can know the type of image I have selected? If it is png or jpg or whatever before uploading it to the database.
First, React Javascript works the exact way Javascript works everywhere, For accessing the image type refer to the below code, I have added the comments for better understanding.
const [imageAsFile, setImageAsFile] = useState('');
const [imageAsUrl, setImageAsUrl] = useState(allInputs);
const [media, setMedia] = useState(null);
const handleImageAsFile = (e) => {
//image var holds the file object which has a type property
const image = e.target.files[0];
console.log(image.type); // this will output the mime, i.e "image/png" or "image/jpg"
setImageAsFile(imageFile => (image));
console.log(imageAsFile);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With