Uploading files from VueJs to Laravel using Axios

I'm having trouble uploading multiple files and I can't seem to figure out what's causing the issue. Everything works fine when I upload just one file, but when I try to modify the code for multiple files, it doesn't work properly. (I'm new to this as well).

Here is the code snippet:

 methods: {
    // File change event handler
    onFileChange(e) {
      this.filename = "";
      var names;
      var link;
      var keys = Object.keys(e.target.files);
      console.log(e.target.files);
      this.numberOfFiles = keys.length;
      console.log("# of files:" + this.numberOfFiles);
      if (keys.length <= 1) {
        this.filename = e.target.files[0].name;
      } else {
        for (var i = 0; i < keys.length; i++) {
          if (e.target.files[i].size > 5000000) {
            console.log(e.target.files[i].name + " is too big.");
          } else {
            this.filename += e.target.files[i].name + ", ";
          }
        }
      }
      for (var i = 1; i <= this.numberOfFiles; i++) {
        this.file = e.target.files[i];
      }

      link = "localhost:8080/upload" + this.filename;

      console.log("names: " + names);

    },

    // Form submission method
    submitForm(e) {
      e.preventDefault();
      let currentObj = this;
      const config = {
        headers: {
          "content-type": "multipart/form-data",
          "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')
            .content
        }
      };

      let formData = new FormData();
      for (var i = 1; i <= this.numberOfFiles; i++) {
        formData.append('file[' + i + ']', this.file[i]);
      }

      // Send upload request using Axios
      axios
        .post("/store_file", formData, config)
        .then(function(response) {
          currentObj.success = response.data.success;
          currentObj.failed = response.data.failed;
          currentObj.filename = "";
        })
        .catch(function(error) {
          currentObj.failed = "No file attached.";
          console.log("No file attached");
        });
    }
  }
};

Below is the HTML template:

<template>
  <b-card class="card" style="margin-top: 50px;">
    <div style="min-height: 100vh; width: 100%;">
      <Notification v-if="success !== ''" :text="success" />
      <Notification v-if="failed !== ''" :text="failed" />
    </div>

    <div class="text-center">
      <h2>PDF Upload</h2>
      <br />
      <div style="max-width: 500px; margin: 0 auto;">
        <form @submit="submitForm" enctype="multipart/form-data">
          <div class="input-group">
            <div class="custom-file">
              <input type="text" placeholder="Email" name="email" id="text" autocomplete="off" />
              <input
                type="file"
                name="filename[]"
                class="custom-file-input"
                id="inputFileUpload"
                multiple
                v-on:change="onFileChange"
              />
              <label class="custom-file-label" for="inputFileUpload"></label>
            </div>
            <div class="input-group-append">
              <input type="submit" class="btn btn-primary" value="Upload" />
            </div>
          </div>
          <br />
          <p v-if="filename !== ''" class="text-danger font-weight-bold">Selected: {{filename}}</p>
        </form>
      </div>
    </div>
  </b-card>
</template>

Current output:

Array
(
    [file] => Array
        (
            [1] => undefined
            [2] => undefined
            [3] => undefined
            [4] => undefined
        )

)

Answer №1

When saving file data to the file property, make sure to push each file in the iteration instead of overwriting the previous assignment. Also, remember to start the iteration from index 0, not from 1:

methods: {
  onFileChange(e) {
    this.filename = "";
    var names;
    var link;
    var keys = Object.keys(e.target.files);
    console.log(e.target.files);
    this.numberOfFiles = keys.length;
    console.log("# of files:" + this.numberOfFiles);
    if (keys.length <= 1) {
      this.filename = e.target.files[0].name;
    } else {
      for (var i = 0; i < keys.length; i++) {
        if (e.target.files[i].size > 5000000) {
          console.log(e.target.files[i].name + " is too big.");
        } else {
          this.filename += e.target.files[i].name + ", ";
        }
      }
    }
    for (var i = 0; i < this.numberOfFiles; i++) {
      this.file.push(e.target.files[i]); //push files instead of assigning 
    }

    link = "localhost:8080/upload" + this.filename;

    console.log("names: " + names);
  },

  submitForm(e) {
    e.preventDefault();
    let currentObj = this;
    const config = {
      headers: {
        "content-type": "multipart/form-data",
        "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content
      }
    };

    let formData = new FormData();
    for (var i = 0; i < this.numberOfFiles; i++) {
      formData.append('file[' + i + ']', this.file[i]);
    }

    //send upload request
    axios
      .post("/store_file", formData, config)
      .then(function(response) {
        currentObj.success = response.data.success;
        currentObj.failed = response.data.failed;
        currentObj.filename = "";
      })
      .catch(function(error) {
        currentObj.failed = "No file attached.";
        console.log("No file attached");
      });
  }
}
};

Answer №2

Here's a different approach to try out: Create an array named 'files', and then use the push method to add each file to it.

v-on:change="onFileChange($event)"

onFileChange(e){
                Array.from( e.target.files).forEach(file => {
                    this.files.push(file);
                });

When passing the files, you can use FormData to handle them:

let formData = new FormData();
this.files.forEach(function (file) {
   formData.append('files[]', file);
 });
},

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

Header on top of table that stays in place with scrolling

I'm facing an issue with a table that contains user-generated data. We are utilizing a plugin known as Clusterize, which allows us to smoothly scroll through large amounts of rows. However, the specific markup required for this plugin seems to be caus ...

The error message "TypeError: 'undefined' is not an object ('_this.props')" indicates that the property '_this

Having trouble solving this issue. Need assistance with evaluating 'this.props.speciesSelection.modalize' <BarcodeInput speciesSelection={this.props.speciesSelection} species={species[0]} barcode={{ manufacturerValue: ...

Allow only users with specific domain to log in with Google Auth using Node Passport

I am currently in the process of setting up Google Auth for an internal system at my workplace. The application heavily relies on a JavaScript client with a Node backend. To make this happen, I decided to go with Passport.js and utilize the passport-google ...

What could be causing the error with firebase Sign In in next.js?

I set up a sign in page to enter email and password for Firebase authentication. The sign up process works fine, but I'm encountering an issue with the sign in functionality. 'use client' import { useState } from 'react'; import { ...

AngularJS: The requested resource does not have the "Access-Control-Allow-Origin" header

Currently developing my web application using AngularJS, I have a file named script.js which contains the following code: var module = angular.module('project', ['ngRoute']); // setting up our routes module.config(function ($r ...

Utilizing a Single Variable Across Multiple Middlewares in nodeJS

I encountered an issue where I am attempting to utilize one variable across two middlewares, but it displays an error stating that the variable is not defined. Here is an example of my situation: //1st middleware app.use((req, res, next) =>{ cont ...

Opencart is displaying a resource as a font even though it was transferred with a MIME type of text/html

Despite searching extensively on Stack Overflow, none of the answers I found have been able to resolve my issue. I am using an Opencart Store with custom typography and encountering the following error: Resource interpreted as Font but transferred with MI ...

Implementing Pagination in Vuetify: A Step-by-Step Guide

I am looking to implement pagination using the Vuetify framework in my VueJS project. The Vuetify Pagination component: <v-pagination v-model="pagination.page" :length="pagination.total / 5" :total-visible="pagination.visible" ...

Avoid changing the regex pattern if it is surrounded by a specific character

I want to change all occurrences of strings enclosed by - with strings enclosed by ~, unless the string is again surrounded by *. For instance, consider this string... The -quick- *brown -f-ox* jumps. ...should be altered to... The ~quick~ *brown -f-ox ...

What is the best way to bring in Javascript files to a specific component along with HTML and CSS?

` <script src="./jquery.min.js"></script> <script src="./bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="./jquery.easing.min.js"></script> <!-- Page level plugin JavaScr ...

Troubleshooting sequential image loading in KineticJS and resolving issues with opacity tween when setting fillPatternImg

In my latest project using KineticJS, I am developing a small app that generates multiple nodes in the form of RegularPolygons. Once the stage has loaded (activated with play();), I proceed to sequentially fill each node with an image pattern using loadIma ...

Many inhabitants - utilizing mongoosejs

Just a simple question, for example with a double reference in the model. Schema / Model var OrderSchema = new Schema({ user: { type : Schema.Types.ObjectId, ref : 'User', required: true }, meal: { ...

Delay the v-alert display after an item is added to the array basket using setTimeout

here is my custom rightTableMenu template <template> <div> <h1 align="center">{{ title }}</h1> <v-alert type="info" icon="mdi-emoticon-sad" v-if="basketStatus"> Empty Basket, please add some to basket < ...

Is there any more Angular code to be bound using ng-bind-html or ng-bind?

Hey there! Just a quick Angular inquiry: <div class="_minimal_size margin_10_middle"> <div class="_50 espaciado_0_20"> <p ng-bind-html="eirana_knows.feedback"></p> </div> <br class="clear"/> </div ...

Transforming characters in a string using Javascript

Currently, I am replacing commas in a textbox. However, how do I go about replacing both a "$" and a comma if they appear together in the same line? function doValidate() { var valid = true; document.likeItemSearchForm.sup.value = document.likeItemSearc ...

Performing an Ajax MySQL query utilizing the text from a link as a reference, across a page

I have a page with several links. When a user clicks on a link, the text from the link is used in the WHERE clause of a MySQL query, and the result is displayed on the page using ajax. I'm trying to run different queries based on multiple ids or clas ...

Develop a JavaScript function to create a DIV element and retrieve the text content using a JavaScript constant

Seeking assistance with creating a JavaScript function to add a dynamic DIV with specific configuration. Current setup: <div class="tooltip" > <font class="textStyleInfo"><b>( ...

Participant joins in the game table and reacts

I am looking to set up a table where players can join and have their usernames displayed at the bottom of the screen just like in other games. How can I achieve this? export const GameStart = (props) => { const params = useParams(); const gameID = p ...

HeaderView in Angular Framework

When exploring the best practices for organizing an AngularJS structure, I came across the recommendation to implement partial views as directives. Following this advice, I created a directive for my app header. In my specific header design, I included a ...

Creating a login page with Titanium Appelerator is a breeze

Looking for guidance on creating a login page using Titanium Appcelerator docs. Struggling to grasp the documentation - any recommendations for tutorials on storing user data in a database, accessing it, and implementing a login system? ...