Reputation: 13
`` Searching how to send a file from a client using a input type=file to a API I found that I should be using a formData. I've done that according to some examples I saw but when I try to see what I sended on the server side it is just undefined.
This is the code on the cliente side:
const [fileList, setFileList] = useState(null);
const files = fileList ? [...fileList] : [];
const handleUploadClick = () => {
if (!fileList) {
return;
}
// Create new FormData object and append files
const data = new FormData();
console.log(files[0], files[0].name)
data.append('file', files[0], files[0].name);
/*
files.forEach((file, i) => {
data.append('file', file, file.name);
});
*/
for (var pair of data.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
axios.post('/api/uploadPostFiles', data, {})
.then( res => {
console.log(res.statusText)
})
alert("File uploaded!")
};
And this is the code on my server side:
app.post("/api/uploadPostFiles", (req, res) => {
let uploadFile = req.files.file
const fileName = req.files.file.name
console.log(fileName)
console.log(uploadFile)
/*other things below but first I need to know I have the correct values*/
The error I receive is:
TypeError: Cannot read properties of undefined (reading 'file')
PD: according to my research i don't have to use content-type = multipart/form-data in the post
I tried playing around with the req, tried req.files, req.file, req.body, but i can't find a way to get the file values
Upvotes: 1
Views: 1294
Reputation: 426
Client side:
axios.post("/api/uploadPostFiles",
{
image:files[0]
},
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(data => console.log(data))
.catch(err => console.log(err))
For the back end you need a middleware for handling multipart/form-data. I use multer. To install multer:
npm install --save multer
Backend:
const multer = require("multer");
const storageEngine = multer.diskStorage({
destination:(req,file,cb)=>{
//destination of ur files
cb(null,"./images")
},
filename: (req,file,cb)=>{
//name of the file. you can name it what ever u want
cb(null,file.originalname);
}
});
const upload = multer({storage:storageEngine});
/*the middleware argument is the property name of the image sent in the
body. in our case its image */
app.post("/api/uploadPostFiles",upload.single("image"),(req,res)=>{
console.log(req.file);
res.send("Image downloaded succesfuly!");
});
sorry if i make some expalanation mistakes my english is bad, i hope i answered your question.
Upvotes: 1