Reputation: 50
I am trying to upload a file using FormData, but the server does not receive the data.
Following a number posts and blogs that conclude setting content type header as multipart/form-data overrides the required format that includes "boundary", I removed the content type header assuming my browser is going to handle the request content type header. The web is flooded with this solution for formdata, but I could not find any case where the browser does not automatically set the content type when FormData is used. My server works fine, because I am able to successfully post requests from a REST client.
This is my API call :
const data = new FormData()
data.append('file', this.state.selectedFile)
const result = await fetch("http://localhost:3000/uploadResume", {
method: "POST",
headers: {
"Authorization": `Bearer ${localStorage.getItem('user_token')}`
},
data: data
})
These are the request headers set by the browser (Google Chrome) :
Is there a browser setting I am missing, or an other potential issue I am overlooking ?
SOLVED I called the API with data set as 'data' instead of 'body' by mistake.
Upvotes: 0
Views: 1872
Reputation: 37825
the Request object expects a body
property
fetch(url, {
// data: data <-- wrong
body: data // <-- correct
})
judging by the small amount of data that you are sending (just one field/file) you could just simply post the data as raw bytes instead of having it be a FormData (makes it a tiny bit easier for the server to pipe the data to a file & doesn't have to process any FormData algorithm) + you would know how large the file is beforehand when receiving it.
fetch(url, {
body: this.state.selectedFile
})
all doe, you lose the filename but maybe you can just stick it in some x-filename header
Upvotes: 1