【问题标题】:Laravel storing only last imageLaravel 只存储最后一张图片
【发布时间】:2019-11-15 12:31:09
【问题描述】:

我正在尝试上传和存储多张图片,但只保存最后一张图片,其余的都被忽略了。

我使用 Nuxt、Axios 和 Laravel 作为 API。

This is the FormData Console.log

And this is the Laravel API response with only the last image added

希望有人能帮我弄清楚发生了什么,在此先感谢

Pug 

input(type='file' ref='files' accept='image/*' multiple @change='handleFilesUpload()' style='display:none')
.text-xs-right.pb-3
    v-btn(@click='$refs.files.click()' color='#B6944C')
       v-icon add

    v-btn(color='green' @click='submitFiles()')
Axios

async submitFiles(){
       let fd = new FormData()
       for(var i = 0; i < this.files.length; i++){
         let file = this.files[i]
         //fd.append('photo[' + i + ']', file)
         fd.append('photo[]', file)
       }
       try{
        await this.$axios.$post(`/albums/${this.$route.params.id}/photos`, fd, {headers:{'Content-Type': 'multipart/form-data'}})
        console.log(...fd)
        alert('uploaded')
        this.files = ''
        //this.$router.push(`/photo/${this.$route.params.id}`)
        //location.reload()
      }
      catch(err){
        console.log(err.response.data)
        alert(err)
      }

     } 
Laravel Controller 

public function store(PhotoInAlbumRequest $request, Album $album){
        $photo = new PhotoInAlbum();
        $photo->photo = $request->photo;

        $images = $request->file('photo');
        if($request->hasfile('photo')){
            foreach($images as $image){
                $filenameWithExt = $image->getClientOriginalName();
                $filename = pathInfo($filenameWithExt, PATHINFO_FILENAME);
                $extension = $image->getClientOriginalExtension();
                $filenameToStore = $filename.'_'.time().'.'.$extension;
                $path = $image->storeAs('photo/images',$filenameToStore,'public');
                $photo->photo = $path;
                $album->photos()->save($photo);
            }
        }
        return new PIAResource($photo);
    }

【问题讨论】:

    标签: laravel axios nuxt.js


    【解决方案1】:

    我解决了它在 Foreach 内移动这 2 行,现在它正在工作(=

    $photo = new PhotoInAlbum();
    $photo->photo = $request->photo;
    

    【讨论】:

      猜你喜欢
      • 2020-04-21
      • 1970-01-01
      • 2020-03-29
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-24
      • 2022-10-17
      相关资源
      最近更新 更多