Reputation: 789
Im trying to understand why my files are not being sent with axios request from frontend while I can send them with Postman.
I have Nodejs backend with multer to accept files like so,
app.use(multer({ storage: multer.memoryStorage() }).array('datafiles', 4))
In backend route I handle this as follows
export const postFarmData = async(req, res, next) => {
console.log(req.files)
for (const file of req.files) {
const json = await csv().fromString(file.buffer.toString('utf-8'))
for(const entry of json) {
const validation = validateDataRow(entry)
if(validation){
await FarmDataModel.create(entry)
}
};
}
res.status(200).json({ success: true, msg: "Post new farm data"})
}
with Postman these are headers
in frontend I select files and make request like s0
const [uploadFile, setUploadFile] = useState()
const handleSubmit = async(e) => {
e.preventDefault()
const dataArray = new FormData();
dataArray.append("datafiles", uploadFile);
const response = await axios.post( API_ROOT,
dataArray, {
headers: {
'Accept': '*/*',
'Content-Type': 'multipart/form-data'
}
})
const result = await response
console.log(result)
}
return <div className="addfile-container">
<form onSubmit={handleSubmit}>
<label htmlFor="files">Select file(s)</label>
<br/>
<input type="file" id="files" name="files" multiple onChange={(e) => setUploadFile(e.target.files)}/>
<br/>
<input type="submit"></input>
</form>
</div>
What happens is that sending from frontend responds ok, but req.files are empty. So no file reaches backend.
With Postman files reach server and are processed ok. What is wrong that my files from frontend are not reaching backend?
EDIT: Adding chrome devtools Post request headers
Upvotes: 0
Views: 1368
Reputation: 3443
Your "file" is in fact a FileList
because you accept multiple files
You should extract them one by one:
dataArray.append("datafiles", uploadFile);
should be
// uploadFile is an HTML input element: <input type="file" id="myfileinput" multiple>
// loop through files
for (let i = 0; i < uploadFile.length; i++) {
const file = uploadFile.item(i);
dataArray.append("file" + i, file);
}
More information: https://developer.mozilla.org/en-US/docs/Web/API/FileList
Upvotes: 2