2

I have writing Single page application using VueJS and Laravel 5.3.

I have developed my back-end API endpoints using Laravel 5.3 and I am not good with front end development for example vueJS. I am trying to upload multiple files using VueJS and Laravel 5.3.

2
  • 1
    Have a look at dropzonejs.com Commented Dec 13, 2016 at 13:37
  • looks good..let me try this one. Thank you Commented Dec 13, 2016 at 15:29

3 Answers 3

5

This might come later than you needed it, however it might still help people that will be looking for this.

First off, use axios library to send your files from your frontend to your backend.

Make sure you use FormData on Javascript side.

Here is a piece of code that will help you process your upload and send it to the server.

< input type = "file"
multiple = "multiple"
id = "attachments"
@change = "uploadFieldChange" >

    // This function will be called every time you add a file
    uploadFieldChange(e) {

        var files = e.target.files || e.dataTransfer.files;
        if (!files.length)
            return;

        for (var i = files.length - 1; i >= 0; i--) {
            this.attachments.push(files[i]);
        }

        // Reset the form to avoid copying these files multiple times into this.attachments
        document.getElementById("attachments").value = [];
    }

submit() {

    this.prepareFields();

    var config = {
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: function (progressEvent) {
            this.percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            this.$forceUpdate();
        }.bind(this)
    };

    // Make HTTP request to store announcement
    axios.post(this.settings.file_management.upload_files, this.data, config)
        .then(function (response) {
            console.log(response);
            if (response.data.success) {
                console.log('Successfull Upload');
                toastr.success('Files Uploaded!', 'Success');
                this.resetData();
            } else {
                console.log('Unsuccessful Upload');
                this.errors = response.data.errors;
            }
        }.bind(this)) // Make sure we bind Vue Component object to this funtion so we get a handle of it in order to call its other methods
        .catch(function (error) {
            console.log(error);
        });

}

Complete solution has a few more lines of code and is wrapped in a Laravel project.

You can find more details on Medium: https://medium.com/@adnanxteam/how-to-upload-multiple-files-via-ajax-vuejs-and-laravel-5-5-file-management-d218c3bbb71c

Sign up to request clarification or add additional context in comments.

Comments

3

If you don't want yo use a plugin, it can be done using FormData.

Example:

// hmtl
<input type="file" multiple ref="file_input" @change="uploadFiles">


//Javascript
uploadFiles () {
  // get the input
  let files = this.$refs.file_input.files

  // assuming you are using the default lint you'll need to add these
  /* global FormData */
  /* eslint no-undef: 2 */
  let data = new FormData

  for (let i = 0; i < files.length; i++) {
     data.append('input_name[]', files[i])
  }

  // assuming you are using vue-resource
  this.$http('url', data).then(response => {
    // handle response
  }).catch(err => {
    // handle error
  })

}

Check the fiddle: https://jsbin.com/hozuwamoci/

3 Comments

Is this upload the file to the server too.. i mean can i get files and store files via server side programming (files sent to server)?
oh i got you...i got files now i am trying to save the file on server.
I checked the fiddle, and tried but i got 'FormData' is not defined error
2

First you shoud import axios like

import axios from 'axios';

in your app.js

then your your component look like

<template>
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">VUe Example Component</div>

                <div class="panel-body">
                        <legend>Upload form</legend>

                        <div class="form-group">
                            <label>Upload Files</label>
                            <input id="upload-file" type="file" multiple class="form-control" @change="fieldChange">
                        </div>




                        <button class="btn btn-primary" @click="uploadFile">Submit</button>

                </div>
            </div>
        </div>
    </div>
</div>
</template>

<script>
export default {
    data(){
      return {
          attachments:[],
          form: new FormData
      }
    },
    methods:{
        fieldChange(e){
            let selectedFiles=e.target.files;
            if(!selectedFiles.length){
                return false;
            }
            for(let i=0;i<selectedFiles.length;i++){
                this.attachments.push(selectedFiles[i]);
            }
            console.log(this.attachments);
        },
        uploadFile(){
            for(let i=0; i<this.attachments.length;i++){
                this.form.append('pics[]',this.attachments[i]);
            }
            const config = { headers: { 'Content-Type': 'multipart/form-data' } };
            document.getElementById('upload-file').value=[];
            axios.post('/upload',this.form,config).then(response=>{
                //success
                console.log(response);
            })
                .catch(response=>{
                    //error
                });
        }
    },
    mounted() {
        console.log('Component mounted.')
    }
}
</script>

this work for me

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.