我在Laravel应用程序中有一个Vue组件,出于某种原因我不得不在这种情况下使用vue2-dropzone-js
,但是我无法弄清楚是否将文件发送到控制器。
第一个问题,在我找到此解决方案之前,axios无法执行multipart/form-data
请求:
methods: {
onSubmit() {
this.item.images = this.$refs.itemImageDropzone.getQueuedFiles();
let formData = new FormData();
for (let i = 0; i < this.item.images.length; i++) {
const file = this.item.images[i];
console.log(file);
formData.append("images[" + i + "]", file);
}
formData.append("name", this.item.name);
formData.append("link", this.item.link);
formData.append("description", this.item.description);
formData.append("price", this.item.price);
axios
.post("items", formData, {
headers: { "Content-Type": "multipart/form-data" }
})
.then(resp => {
this.$emit("item-added", resp.data.data);
this.images = [];
})
.catch(err => console.error(err));
}
}
好的,它可以正常工作,它接受了请求并且没有给我422
错误代码。但是,随后出现了新问题。控制器向我发送此错误:
“ message”:“调用成员函数store()时为null”
当我执行console.log
请求时,它会在images
上显示一个空对象,该对象是我之前创建的算法的补充。
这是我在进行console.log
来检查dropzone值时得到的结果:
有人可以帮我吗?
这是我的控制器代码:
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(StoreItem $request)
{
// collect item data without images
$item = collect($request->validated())
->except('images')
->toArray();
// create item data
$item = Item::create($item);
$images = $request->file('images');
// check if the request has images file and the count is more than one
if ($request->hasFile('images') && count($images) > 1) {
// iterate over images
foreach ($images as $image) {
// store file in local storage
$file = $request->file($image)->store('//uploads//', 'local');
// create image data
$image = ItemImage::create(['path' => $file]);
// associate each image with the item
$image->items()->associate($item);
}
// return items with images relation
return response()->json(
$item->load('images')
);
}
// store file in local storage
$file = $request->file('images')->store('//uploads//', 'local');
// create image data
$image = ItemImage::create(['path' => $file]);
// associate each image with the item
$image->items()->associate($item);
// return items with images relation
return response()->json(
$item->load('images')
);
}
编辑
这是我的StoreItem.php
中的内容:
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|string|max:100',
'link' => 'required|string',
'description' => 'required|string',
'price' => 'required|numeric',
'images' => 'required',
'images.*' => 'image|max:2048|mimes:jpeg,png,jpg,gif,svg',
];
}