5

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.

1
  • Use multipart/form-data instead of application/x-www-form-urlencoded Commented Apr 6, 2018 at 6:40

2 Answers 2

9

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'

Sign up to request clarification or add additional context in comments.

2 Comments

Removing 'Content-Type' from header worked for me
when i remove the header, chrome sends it as plain text and it doesn't work
0

I'm uploading excel file and passing it to fetch method and working as I expected way

            const formData = new FormData()
            formData.append('file', payload)

            const createXHR = () => new XMLHttpRequest()

            fetch('https://localhost:8080/file/', {
                body: formData,
                createXHR,
                method: 'POST'
            }).then(response => {
                return response.json()
            }).then(res => {
                console.log(res, 'res')
            })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.