I cannot upload files in React.js with FormData. Basically my console.log is empty when I try to check the formData or formData.entries(), why?
const FileUpload = ({ src, sendImage, input }) => {
const [source, setSource] = useState();
const handleUpload = (e) => {
const file = e.target.files;
const url = URL.createObjectURL(file[0]);
const fileName = file[0].name;
setSource(url);
const formData = new FormData();
formData.append("image", url);
console.log(formData.entries());
sendImage({ url: formData, fileName: fileName, mime: type });
};
return (
<Button variant="contained" component="label" sx={{ marginTop: "15px", borderRadius: 2 }}>
<input hidden accept={input === "audio" ? "audio/*" : "video/*"} type="file" onChange={handleUpload} />
UPLOAD
</Button>
>Solution :
it seems like that you are passing the url of uploaded file insted of the file it self to FormData.you should append the actual image to FormData like this
const formData = new FormData();
formData.append("image", file[0]); // append the actual file, not the URL
console.log(formData.entries());
sendImage({ url: formData, fileName: fileName, mime: type });
and also formData.entries() returns an iterator so you need to iterate over it to see its value you can use spread operator
console.log([...formData.entries()]);