Vue js和Laravel中的多图片上传器

时间:2020-07-24 08:19:41

标签: laravel vue.js

 When i select multiple image it work fine.but my images is array is coming in this order

这是我用于多个图像上传器的模板文件和脚本文件。当我选择多张图像时,它可以正常工作,但是我的数组按照给定的图片顺序排列。那么我该如何解决呢?

<input type="file" class="form-control" multiple accept="image/jpeg" @change="uploadImage"/>
<div  v-for="(image, key) in images" :key="key">
     <img :ref="'image'" class="preview" style="width:200px;"/>
      {{ image.name }}
 </div>

 

<script>
export default {
    data() {
        return {
            images: [],

        }
    },
    methods: {
        uploadImage(e) {
            let vm = this;
            var selectedFiles = e.target.files;
            for (let i = 0; i < selectedFiles.length; i++) {
                this.images.push(selectedFiles[i]);
            }
            for (let i = 0; i < this.images.length; i++) {
                let reader = new FileReader();
                reader.onload = (e) => {
                    this.$refs.image[i].src = reader.result;
                    console.log(this. image[i].src);
                };
                reader.readAsDataURL(this.images[i]);
            }
        },

    }
}

和我的控制器上传多张图片。行吗?

public function addProductImages(Request $request){
    if($request->isMethod('post')){
        $data=$request->all();
        dd($data);
        if($request->hasFile('images')){
            $images=$request->file('images');

            foreach($images as $key=>$image){
                $productImage=new ProductsImage();
                $image_tmp=Image::make($image);
                $extension=$image->getClientOriginalExtension();
                $imageName=rand(111,999999).time().'.'.$extension;
                $large_image_path='backend/dist/products/alt/large/'.$imageName;
                $small_image_path='backend/dist/products/alt/small/'.$imageName;
                Image::make($image_tmp)->save($large_image_path);
                Image::make($image_tmp)->resize(520,600)->save($small_image_path);
                $productImage->image=$imageName;
                $productImage->product_id='1';
                $productImage->save();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

如果您尝试预览上传的图像,则代码可以简化为:

<div id="app">
<input type="file" class="form-control" multiple accept="image/jpeg" @change="uploadImage"/>
<div  v-for="(image, key) in images" :key="key">
     <img :src="image.src" class="preview" style="width:200px;"/>
      {{ image.file.name }}
 </div>
  </div>
</template>

<script>
export default {
    data() {
        return {
            images: [],

        }
    },
    methods: {
        uploadImage(e) {
            var selectedFiles = e.target.files;
            for (let i = 0; i < selectedFiles.length; i++) {
                let img = {
                    src: URL.createObjectURL(selectedFiles[i]),
                    file: selectedFiles[i],
                }
                this.images.push(img);
            }
        },

    }
}
</script>