简体   繁体   中英

Multiple file upload using Laravel & Vue JS

so I've been trying to upload multiple image file using Vue JS with Laravel at server side.

My template vue

<input type="file" id = "file" ref="file" v-on:change="onImageChange" multiple />

My Javascript code

<script>
 export default {
  data(){
    return{
      product: {},
      image: '',
    }
  },
  created() {
    let uri = `/api/product/edit/${this.$route.params.id}`;
    this.axios.get(uri).then((response) => {
        this.product = response.data;
    }); 
  },
  methods:{
    onImageChange(e){
      let files = e.target.files || e.dataTransfer.files;
      if (!files.length)
       return;
       this.createImage(files[0]);
    },
    createImage(file){
       let reader = new FileReader();
       let vm = this;
       reader.onload = (e) => {
         vm.image = e.target.result;
       };
       reader.readAsDataURL(file);
    },
    replaceByDefault(e) {
      e.target.src = this.src='/uploads/products/default_image.jpg';
    },
    saveImage(e){

        e.preventDefault()

        var file = document.getElementById('file').files;

        let formData = new FormData;
            formData.append('productId', this.product.id)
            formData.append('file', file[0])

        axios.post('/api/product/image/add', formData, {
            headers: {'Content-Type': 'multipart/form-data'}
        }).then((response) => {
            this.$router.push({name: 'view',params: { id: this.product.id }});
            });
     }

    }
   }
  </script>

I saw somewhere the internet that in vue you can use looping the formData.append but how do i catch the data in the server side. Here is my ProductController

  $saveImage = new Gallery;
  $saveImage->product_id = $request->productId;

  $file = request()->file('file');
  $file_name = time().$file->getClientOriginalName();
  $path = $imgUpload = Image::make($file)->save(public_path('/uploads/products/' . $file_name));

  $saveImage->path = '/uploads/products/'.$file_name;
  $saveImage->status = 1;

  $saveImage->save();
  return "success";

Thank you very much guys!

you can use request()->file('file') to get files. but you have to add some changes in your vue source when you are trying to send an array of files.

Vue

let formData = new FormData;
formData.append('productId', this.product.id)
// append files
for(let i=0; i<file.length; i++){
  formData.append('file[]', file[i])
}

useing file[] instead of file will generate an array of files in request payload. then in laravel side of code you can use request()->file('file') to get that array of files. but if you want just one of them (for example: first one) you can use request()->file('file.0') to get that file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM