Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading a file using "fetch" in reactJS

Uploading a file using "fetch" in reactjs

I am trying to upload a file using ReactJS.

handleUploadfile = (event) => {
        event.preventDefault();
        const data = new FormData();
        data.append('photo',event.target.files[0] );
        data.append('name', 'Test Name');
        data.append('desc', 'Test description');
        fetch("http://localhost:3001/todo/upload", {
             method: 'POST',
             headers: {
                 'Accept': 'application/json',
                 'Content-Type': 'application/x-www-form-urlencoded'
             },
             body: data
        }).then((response) =>  {
           return response.text();
        })
    }

For some reason I am not able read the files at nodejs(+multer) server using:

req.files

which shows "undefined" at post router.

like image 444
Vara Prasad Boddu Avatar asked Mar 06 '23 12:03

Vara Prasad Boddu


1 Answers

Finally I found the solution

I had to remove the 'Content-Type' from headers section and it worked out in nodejs using multer.

Using the "multipart/form-data"

'Content-Type': 'multipart/form-data'

requires us to set boundaries and hence it is throwing error at nodejs "Error: Multipart: Boundary not found"

Using the "application/x-www-form-urlencoded"

'Content-Type': 'application/x-www-form-urlencoded'

I am getting the req.body filled but as string but not able to access the individual values.

Hence final solution is removal of 'Content-Type'

like image 138
Vara Prasad Boddu Avatar answered Mar 18 '23 16:03

Vara Prasad Boddu