我正在尝试使用 ReactJS 中的 .fetch()
上传文件作为前端,Laravel 作为后端。我的 ReactJS 代码如下所示
update= (event) => {
let uploadImage = event.target.file;
let form = new FormData()
form.append('uploadImage',uploadImage)
fetch('http://127.0.0.1:8000/api/addresses/upload', {
headers: {
'Authorization': 'Bearer ' + Auth.getToken(),
'Content-Type': 'multipart/form-data',
},
method: "POST",
body: form,
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
我的 Laravel 代码如下所示
public function fileUpload(StoreImageRequest $request)
{
$image = $request->uploadImage;
$imagename = time() . $image->getClientOriginalName();
$destinationPath = public_path('/images');
$uploadValue = $image->move($destinationPath, $imagename);
if ($uploadValue) {
return response()->json($imagename);
}
}
出现如下错误
和
问题出在哪里?
最佳答案
这是因为您使用表单字段名称 avatar
上传图片,但在您的 Laravel 方法中您使用 uploadImage
访问它。
所以您可以尝试将其更改为以下内容:
$request->avatar
请结帐the Laravel Files documentation并确保您遵循他们的最佳做法。
关于reactjs - 在 ReactJS 中使用 .fetch() 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50736718/