Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload multiple file with vue js and axios

I am trying to upload multiple images using vuejs and axios but on server side i am getting empty object. I added multipart/form-data in header but still empty object.

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

    /*
      Iteate 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, …}

like image 325
weaver Avatar asked Feb 04 '19 16:02

weaver


1 Answers

You forgot to use $refs. Add ref to your input:

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

Next, access your files like this:

submitFiles() {

    let 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 be works.

like image 144
Daniel Avatar answered Oct 15 '22 13:10

Daniel