Reputation: 179
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.
Upvotes: 5
Views: 20935
Reputation: 20138
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')
})
Upvotes: 0
Reputation: 179
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'
Upvotes: 9