我正在努力通过Vue,Laravel和Axios将图像和几个文本/数字数据字段上传到MySQL数据库。
这是我的Vue组件中的方法:
addProductToShop() {
const imageData = this.$refs.inputUpload.files[0];
const formData = new FormData();
formData.append("image", imageData);
axios
.post("api/createProduct", {
formData,
...this.newProduct
})
.then(res => {
console.log(res);
});
},
这是我的Laravel控制器中的方法:
public function create(Request $request)
{
$product = Product::create([
'name' => $request->name,
'price' => $request->price,
'amountInStock' => $request->amountInStock,
'image' => $request->image->store('ProductImages', 'public'),
'measuringUnitId' => $request->measuringUnitId,
'categoryId' => $request->categoryId,
'shopId' => $request->shopId,
]);
return response()->json([
'status' => 'success',
'message' => 'Product added seccessfully',
'product' => $product
], 200);
}
这是望远镜中的请求正文:
{
"formData": [],
"name": "111",
"categoryId": null,
"price": "111",
"amountInStock": "111",
"measuringUnitId": 2,
"visability": true
}
这是我得到的错误:Call to a member function store() on null
我尝试添加多格式数据头:
headers: {
'Content-Type': 'multipart/form-data'
}
但是,他们生成了此错误:Missing boundary in multipart/form-data POST data in Unknown on line 0
因此,它们现在已经过时了,因为axios基于formData
知道了正确的FormData()
。
有人可以指出我在做什么错吗?预先感谢!
答案 0 :(得分:1)
此处错误:
'image' => $request->image->store('ProductImages', 'public')
正确的方法:
'image' => $request->file('image')->store('ProductImages', 'public')