File Upload using vuetify 2 v-file-input and axios
First of all, you have two bugs in code:
Where you're preparing
FormData
object. You can't usefor-in
loop for iterating an array of files here sincefor-in
loops over enumerable property names of an object. You can usefor-of
loop instead.You're using
formData
in brackets. You should passFormData
instance, not JSON. To send aditional paramaters like"test"
usingFormData
doformData.append("test", "foo bar")
Also check that your backend properly handles multipart/form-data
data. If your backend is in Node.js
and Express.js
then you should use proper body parser middleware, for example multer
Here is a working example:
Node.js/Express.js backend:
const multer = require("multer"),... router.post("/upload-files", multer().array("files"), function (req, res) { console.log("body: ", req.body); console.log("files:", req.files); return res.sendStatus(200);});
frontend:
submitFiles() { if (this.files) { let formData = new FormData(); // files for (let file of this.files) { formData.append("files", file, file.name); } // additional data formData.append("test", "foo bar"); axios .post("/upload-files", formData) .then(response => { console.log("Success!"); console.log({ response }); }) .catch(error => { console.log({ error }); }); } else { console.log("there are no files."); }}
Note that you don't need to set Content-Type
header manually when you pass FormData
as a POST
request body