Uploading Files with Vuetify 2 v-file-input and AxiosIn this tutorial, we

After researching extensively on the topic, I reviewed questions such as file-upload-in-vuetify and vuetify-file-uploads, but unfortunately, the solutions provided did not work for me.

My current challenge involves utilizing Vuetify 2's <v-file-input> to upload multiple PDF files. Even though I have created a FormData object and appended all the necessary files, when I try to submit, the data does not reach my backend as expected - instead, I receive an empty object. Here is a snippet of my code:

Template:

<v-layout>
    <v-flex>
      <v-file-input show-size counter chips multiple label="Arquivo Geral" ref="myfile" v-model="files"></v-file-input>
    </v-flex>
    <v-flex>
      <v-btn color="primary" text @click="submitFiles">test</v-btn>
    </v-flex>
</v-layout>

Script:

data() {
    return {
        files: null,
    }
}
methods: {
    submitFiles(){
        let formData = new FormData()

        if(this.files){

            for( let file in this.files){
                formData.append("cave", file)
            }

            console.log(formData.getAll("cave"))
            console.log(this.files)
            axios.post('https://eniwp6w65oc77.x.pipedream.net/', 
                        {
                            files: formData,
                            test: "test"
                        }, 
                        { 
                            headers: { 
                                'Content-Type': 'multipart/form-data'
                            } 
                        }).then( response => {
                            console.log('Success!')
                            console.log({response})
                        }).catch(error => {
                            console.log({error})
                        })
        }
        else {
            console.log('there are no files.')
        }
    }
}

Upon inspecting the response body and request header in requestbin:

Body:

{
    "files": {},
    "test": "test"
}

Header:

host: eniwp6w65oc77.x.pipedream.net
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,pt;q=0.8,gl;q=0.7
Cache-Control: no-cache
Content-Type: multipart/form-data
Origin: http://localhost:8000
Pragma: no-cache
Referer: http://localhost:8000/
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36
Content-Length: 28
Connection: keep-alive

Answer №1

Firstly, it's important to address two bugs in the code:

  1. One issue is with how the FormData object is being prepared. Using a for-in loop to iterate over an array of files is incorrect as it loops through enumerable property names of an object. Instead, opt for a for-of loop.

  2. The second bug involves using formData in brackets. The correct approach is to pass the instance of FormData, not JSON. To include additional parameters like "test" with FormData, use

    formData.append("test", "foo bar")

Ensure that your backend properly handles data in multipart/form-data format. If you are using a backend in Node.js and Express.js, make sure to utilize appropriate body parser middleware such as multer

Below is a functional example:

Backend in Node.js/Express.js:

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.");
    }
}

Remember, there is no need to manually set the Content-Type header when passing FormData as the request body for a POST request

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating checkbox Icon in Yii2

Is there a way to customize the checkbox icon when it is checked in Yii2? Currently, I am adding a checkbox inside a div along with an icon: <i class="fa fa-check-circle icon-check-circle"></i>. However, the checkbox shows a default check symbo ...

Transferring information in JSON format from an API to a JavaScript variable

Hi there, I'm new to json/javascript so your patience is appreciated. I am receiving json data from an API URL that looks like this: { "employees": [ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstN ...

Encasing a variety of child elements within a div container

My goal is to group a range of children elements within a div so that I can manipulate them collectively in different locations. The challenge arises from having a list with randomly generated li tags, and no matter how many appear, I need every batch of t ...

Steps for setting all textareas on a website to "readonly" mode

My website contains numerous textareas but they currently do not have the read-only attribute. It would be very time-consuming to manually add the readonly attribute to each one. Is there a more efficient method to make all textareas read-only? ...

Using MVC4 and jQuery to unselect items from an Html.CheckboxListFor

In my search page, I am utilizing jQuery to toggle the visibility of different sections based on user input. Specifically, I have a Html.Textbox and Html.CheckboxListFor that are shown or hidden depending on whether there is any input in the textbox or if ...

Implement a formatter function to manipulate the JSON data retrieved from a REST API within the BootstrapVue framework

My bootstrap-vue vue.js v2.6 app is receiving JSON data from a REST API. The data structure looks like this: { "fields": [ { "key": "name", "label": "name", & ...

Struggling with making JSON.parse() function properly in a Discord Bot

I have a separate JSON file connected like this const Players = require('./Database/Players.json'); and a parser that handles the code client.on('message', message => { if (message.content.toLowerCase() ==='smack activate ...

Vue wait for completion of external request

One challenge I'm facing in my Vue application is that a page with an animation on route enter experiences a drop in frames from 60 to 20fps when an embedded Vimeo video is present. It seems that the request to the Vimeo server delays the animation st ...

The HTML div captured with html2canvas is incomplete

I am currently developing a meme editor website utilizing the html2canvas library available at Below is the HTML code for the div I aim to capture: <div class="container"> <div id="theUserMeme"> <div class=& ...

What are the steps for implementing pytesseract on a node.js server?

While working on my node.js server, I encountered an issue when using child-process to send an image to a python script. Although I can successfully read the image in the python script, I encounter an error when attempting to convert it to text using pytes ...

Having trouble with filtering an array using the some() method of another array?

When utilizing the code below, my goal is to filter the first array by checking if the item's id exists in the second array. However, I am encountering an issue where the result is coming back empty. dialogRef.afterClosed().subscribe((airlines: Airli ...

Lack of animation on the button

Having trouble with this issue for 48 hours straight. Every time I attempt to click a button in the top bar, there is no animation. The intended behavior is for the width to increase and the left border color to change to green, but that's not what&ap ...

Secure Flask API used for serving JSON files to a basic HTML, JavaScript, and CSS web application

I have developed a basic web application that will display data in a table and be updated on a weekly basis. To perform this update, I utilize Python code in the backend to scrape and modify data before storing it in a SQLite database. After some researc ...

Acquire a set of picture cards for displaying in a grid layout

After creating a cardArray to store card objects, I went through each item in the array to generate images as cards. These card images were then appended to the grid div as children. Additionally, I set up an event listener for the shuffle button. However, ...

Streaming live video on the website

Hi there! I'm looking to integrate live video capturing into an HTML/JavaScript site for a presentation. However, I'm not sure where to start my search. Can anyone point me in the right direction? :) The live video will be captured by a camera o ...

Unlock the Power of Sockets in JavaScript and HTML

How can I work with sockets in JavaScript and HTML? Could HTML5 features be helpful? Are there any recommended libraries, tutorials, or blog articles on this topic? ...

Angular Dynamic Table Column Adaptor

Recently, I came across the adpt-strap table lite and decided to experiment with it. Here is the JSfiddle link for the project I was working on: http://jsfiddle.net/cx5gm0sa/ My main goal was to dynamically hide or show a column. In my code, I added $scop ...

Having trouble aligning material-ui GridList in the center

I am currently working with a GridList in order to display Cards. The styling for these components is set up as shown below: card.js const useStyles = makeStyles({ card: { maxWidth: 240, margin: 10 }, media: { heigh ...

Issue detected: The validation form is encountering errors due to a blank textarea when utilizing jQuery validate and AJAX for

I am currently working on a spring project that involves registering comments on a specific system design. The page layout for this task is as follows: <form id="formularioCadastroComentario" role="form" method="POST" class="form-horizontal"> &l ...

Vessel situated after the helm

There seems to be an issue with my toolbar and sidenav overlapping the contents of my container. I thought about adding a top margin to the container to fix the problem caused by the toolbar, but adjusting the sidenav in the same way creates display probl ...