多个插入图像Laravel,Vue,Axios

时间:2019-10-24 09:02:39

标签: laravel vuejs2 axios intervention

这是我第一次为vue js laravel创建多个上传文件。我设法在laravel中创建了多个图像,但是只有一个存储在数据库中与输入的请求图像不同。像这样的东西是我的代码。

在我的控制器laravel中。

public function storeProduct()
{

    $data = $this->request->all();

    $query['gallery'] = new ProductGallery;

    if ($this->request->hasFile('images')) {
        if (count($this->request->images) > 1) {
            foreach($this->request->file('images') as $file){

                //filename to store
                $query['gallery']->product_id = 2;
                $filename = md5($file . time()) . '.jpg';

                Storage::disk('public')->put($filename, file_get_contents($file));

                $path = public_path('storage/article-image/'.$filename);
                Image::make($file)->save($path);
                $query['gallery']->file_path = 'article-image/'.$filename;                       
                $query['gallery']->save(); 
            }
        }else {
            return "not array";
        }
    }
    return "Success";
}

在Vue Js模板中。

<template>
  <div class="file-input">
    <label for="file">Select a File</label>
    <input type="file" id="file" @change="onInputChange" multiple>
  </div>
</template>

data() {
  return {
    files: [],
    images: [],
  }
},
methods: {
    onInputChange(e) {
        const files = e.target.files;
        Array.from(files).forEach(file => this.addImage(file));
    },
    addImage(file) {
        if (!file.type.match('image.*')) {
            this.$toastr.e(`${file.name} is not an image`);
            return;
        }
        this.files.push(file);
        const img = new Image(),
            reader = new FileReader();
        reader.onload = (e) => this.images.push(e.target.result);
        reader.readAsDataURL(file);
    },
    upload() {
        const formData = new FormData();
        this.files.forEach(file => {
            formData.append('images[]', file, file.name);
        });
        axios.post('http://localhost.pro/api/v1/product-store', formData)
            .then(response => {
                console.log(response);
            })
    }
}

请帮助,对不起,我的英语是被动的。谢谢

0 个答案:

没有答案