【问题标题】:Multiple file upload using Laravel & Vue JS使用 Laravel 和 Vue JS 上传多个文件
【发布时间】:2020-11-28 10:07:05
【问题描述】:

所以我一直在尝试在服务器端使用 Vue JSLaravel 上传多个图像文件。

我的模板 vue

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

我的 Javascript 代码

<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>

我在互联网某处看到在 vue 中您可以使用循环 formData.append 但我如何在服务器端捕获数据。这是我的 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";

非常感谢你们!

【问题讨论】:

    标签: javascript laravel vue.js file-upload


    【解决方案1】:

    您可以使用request()-&gt;file('file') 获取文件。但是当您尝试发送文件数组时,您必须在 vue 源中添加一些更改。

    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])
    }
    

    使用file[] 而不是file 将在请求负载中生成一个文件数组。 然后在代码的 laravel 端,您可以使用 request()-&gt;file('file') 来获取该文件数组。但如果您只想要其中一个(例如:第一个),您可以使用 request()-&gt;file('file.0') 获取该文件。

    【讨论】:

      猜你喜欢
      • 2019-06-28
      • 1970-01-01
      • 2018-08-26
      • 2022-10-07
      • 2020-09-25
      • 2020-04-09
      • 2021-07-15
      • 2021-02-26
      • 2020-11-14
      相关资源
      最近更新 更多