[Vuejs]-VueJs sending files to laravel (upload)

0👍

When storing file data to the file property, in each iteration, you reset the previous assignment, instead of adding it as an array item to the file, so you should push it. Also, start iteration from 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, don't assign 
    }

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

0👍

try this way…
create a array call files, and try to push each file

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

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

when passing

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

Leave a comment