Reputation: 197
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.
Upvotes: 4
Views: 15496
Reputation: 2044
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);
}
Upvotes: 3