我正在尝试上传和存储多张图像,但是只保存了最后一张图像,其余的仅被忽略了。
我正在使用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);
}
答案 0 :(得分:0)
我解决了在Foreach内部移动这2行的问题,现在它正在工作(=
$photo = new PhotoInAlbum();
$photo->photo = $request->photo;