繁体   English   中英

使用 Laravel 和 Vue JS 上传多个文件

[英]Multiple file upload using Laravel & Vue JS

所以我一直在尝试在服务器端使用带有LaravelVue JS上传多个图像文件。

我的模板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但我如何在服务器端捕获数据。 这是我的产品控制器

  $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";

非常感谢你们!

您可以使用request()->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()->file('file')来获取该文件数组。 但如果您只想要其中一个(例如:第一个),您可以使用request()->file('file.0')来获取该文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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