Vue js and axios make it easy to upload multiple files at once

I am encountering an issue where I am attempting to upload multiple images using vuejs and axios, but the server side is receiving an empty object. Despite adding multipart/form-data in the header, the object remains empty.

submitFiles() {
    /*
      Initialize the form data
    */
    let formData = new FormData();

    /*
      Iterate over any file sent over appending the files
      to the form data.
    */
    for( var i = 0; i < this.files.length; i++ ){
      let file = this.files[i];
      console.log(file);
      formData.append('files[' + i + ']', file);
    }

    /*`enter code here`
      Make the request to the POST /file-drag-drop URL
    */
    axios.post( '/fileupload',
      formData,
      {
        headers: {
            'Content-Type': 'multipart/form-data'
        },
      }
    ).then(function(){
    })
    .catch(function(){
    });
  },

HTML:

<form method="post" action="#" id="" enctype="multipart/form-data">
    <div class="form-group files text-center" ref="fileform">
        <input type="file"  multiple="multiple">
        <span id='val'></span>
        <a class="btn"  @click="submitFiles()" id='button'>Upload Photo</a>
        <h6>DRAG & DROP FILE HERE</h6>
    </div>

My Server side code:

class FileSettingsController extends Controller
{
    public function upload(Request $request){
        return $request->all();
    }
}

Output:

{files: [{}]}
files: [{}]
0: {}

Console.log() result:

File(2838972) {name: "540340.jpg", lastModified: 1525262356769, lastModifiedDate: Wed May 02 2018 17:29:16 GMT+0530 (India Standard Time), webkitRelativePath: "", size: 2838972, …}

Answer №1

Don't forget to utilize $refs. Make sure to add ref to your input:

<input type="file" ref="file" multiple="multiple">

Then, you can access your files like this:

submitFiles() {

    const formData = new FormData();

    for (var i = 0; i < this.$refs.file.files.length; i++ ){
        let file = this.$refs.file.files[i];
        formData.append('files[' + i + ']', file);
    }

    axios.post('/fileupload', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        },
      }
    ).then(function(){
    })
    .catch(function(){
    });
},

This should work now.

Answer №2

For those who are curious about sending additional data along with it, here is a simple method:

formData.append('title[' + this.title + ']', title);
formData.getAll('photos', 'title');

Answer №3

To implement the Composition API, you can use the following code snippet:

const uploadedFiles = ref([])

function upload() {
  let formData = new FormData()
  for (let file of uploadedFiles.value) {
    formData.append('files', file)
  }
  axios.post('/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
  .then((response) => {
    // Handle response here
  })
}

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

Vue: add a CSS class to products when they are in the shopping cart

As I delve into creating a shopping cart using laravel + vue, I am encountering a major obstacle related to vue's functionality. Within my cart component, the goal is to allow users to effortlessly add or remove products by simply clicking. When a pr ...

Is it possible to directly utilize functions from an imported JavaScript library, such as Change Case, within the template of a Vue component?

After successfully importing and using the Change Case library within the <script></script> element of a Vue component, I now seek to directly utilize the Change Case functions in the template itself. As of now, my understanding is that when d ...

What steps can be taken to resolve the error message "t.onSubmit is not a function" that occurs upon form submission?

Upon submitting a form, it should trigger the onSubmit method function. However, an error is being returned instead: TypeError: "t.onSubmit is not a function". I've attempted to address this issue by researching similar problems and solutions provide ...

Issue with setting cookies on the client side when using NodeJS, VueJS, and express-session

I have been working on an app that already has its own infrastructure. My current task is to integrate a session-cookie mechanism, but I've been struggling to make the cookies set on the client side after spending a significant amount of time investig ...

Leveraging an external global variable file that is not incorporated into the bundle

I have a JavaScript file dedicated to internationalization. I am looking for a way to provide this file to clients for them to edit without requiring me to rebuild the entire project. Currently, I store this file in the static folder so it is included in ...

Unlocking the variables within a v-for loop post-mounted: A guide to accessing and updating them

I have a question regarding my code snippet below. The calculation of Ending Inventory involves adding the beginningInventory, newInventory, and totalSold values. How can I access the value property of endingInventory in order to update it? Any assistance ...

Unable to show information in Next.js Strapi integration

I have set out to create a basic task management website as a way to delve into the world of full stack development. My tech stack includes Next.js and Strapi, but I've hit a roadblock. Despite my best efforts, I can't seem to get the server data ...

Tips for passing props while clicking on a v-data-table:

I am currently facing an issue in my app while using v-data-table. I am able to pass props with an extra slot, but I want the entire row to be clickable in order to open a dialog with the prop item: <template v-slot:item.actions="{ item }"> ...

turn off date selection in vue date picker

I am working on disabling specific dates within a date picker. However, my current approach doesn't seem to be fully functional. <v-date-picker v-model="dates3" :max-date="today"> </v-date-picker> data( ...

What is the process of triggering a forceUpdate in setup in Vue 3?

Is there a way to force Update in the setup function of vue3? In the Options API, I can simply use this.$forceUpdate() to achieve this. However, how can we accomplish the same thing in the setup function of vue3? ...

Is there a way to modify the text color within the thumb-label of the Vuetify v-slider component?

Lately, I've been facing some challenges and my objective is to change the color of the thumb label on my v-slider to a custom one that is defined in the component's design. Can anyone provide guidance on how to achieve this? Regards, Joost ...

I'm struggling to understand how to interpret this. The v-tab function seems to be generating a button with various properties, but I'm unsure which specific property is related to

The V-tab below generates the button known as the right one on the v-app-bar: https://i.stack.imgur.com/DzNmq.png <v-tab :to="'/demo'" active-class="text--primary" class=&quo ...

When processing a response from the backend (using express js), cookies are not being received in the browser while on localhost

I'm currently facing some difficulties with implementing authorization cookies within my application. Whenever I attempt to send a GET request to my API (which is hosted on port 8080) from my React frontend (running on port 3000), the cookies that I ...

When should separate controllers be created for a list of values in a Laravel REST API?

Imagine I have a straightforward API for user registration. This API collects basic information like Name, email, state, gender, and marital status for each user. I already have database tables pre-populated with ids for state, gender, and marital status o ...

Is there a method to directly download large files from the server without having to wait for the blob response?

I'm currently working on video file requests using axios. I have set the requests with responseType: blob to create a video player once the response is received with window.URL.createObjectUrl(). However, I also have a button that allows the user to d ...

Ensuring the correct order of script, template, and style tags in Vue using a linter

Looking to implement a new linter rule that verifies the sequence of tags: <script>, <template>, and <style>. By default, Vue places <template> first, but I believe <script> should come first as it holds more importance. It w ...

Are the frameworks Vue, Angular, and React known for

During a conversation, I came across an interesting viewpoint criticizing popular frameworks such as Angular, Vue, and React. It was argued that these frameworks have a significant disadvantage: apart from the API part that interacts with the server's ...

How to retrieve the localhost URL in Laravel with Transbank integration

I am a complete beginner in using Laravel. I have been working on a project involving Transbank payments, and everything seems to be working fine. However, I am facing an issue when trying to return to my localhost path after a transaction. When running L ...

Tips for streamlining repetitive code in Vue 3 Composition API (such as router and store integration)

When using the Vue 3 Composition API, it is necessary for each view to include the following: import { useRouter, useRoute } from 'vue-router' import { useStore } from 'vuex' export default { setup() { const router = useRo ...

Ensure that the modal remains open in the event of a triggered keydown action, preventing it from automatically closing

I am currently toggling the visibility of some modals by adjusting their CSS properties. I would like them to remain displayed until there is no user interaction for a period of 3 seconds. Is there a way to achieve this using JavaScript? Preferably with Vu ...