Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cannot upload files in React.js with FormData

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading