在 ReactJS 中使用 .fetch() 上传文件
File upload using .fetch() in ReactJS
我正在尝试在 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 并确保您遵循他们的最佳做法。
我遇到了同样的问题。我通过删除内容类型修复了它。
请查看这篇文章
https://upmostly.com/tutorials/upload-a-file-from-a-react-component
我正在尝试在 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 并确保您遵循他们的最佳做法。
我遇到了同样的问题。我通过删除内容类型修复了它。
请查看这篇文章
https://upmostly.com/tutorials/upload-a-file-from-a-react-component