File Upload using vuetify 2 v-file-input and axios File Upload using vuetify 2 v-file-input and axios vue.js vue.js

File Upload using vuetify 2 v-file-input and axios


First of all, you have two bugs in code:

  1. Where you're preparing FormData object. You can't use for-in loop for iterating an array of files here since for-in loops over enumerable property names of an object. You can use for-of loop instead.

  2. You're using formData in brackets. You should pass FormData instance, not JSON. To send aditional paramaters like "test" using FormData do formData.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