我尝试使用Postman上传图像,并且图像存储在首选目录中,完整路径存储在数据库中,但是我收到错误响应
“消息”:“在字符串上调用成员函数extension()”,
这是我的代码
public function store(AvatarUploadRequest $request, UserService $userService) {
$user = $request->user();
try {
$file = $request->file('avatar');
$file = url("/avatars") . "/" . $user->uuid . ".jpg";
$destinationPath = "avatars";
$user->avatar = $request->file('avatar')->move($destinationPath, $file)
->getClientOriginalExtension();
$user->avatar = $file;
$user->save();
$userService->updateAvatar($user, $file);
}
catch (\Exception $e) {
return jsonApiResponse([
'avatar' => $e->getMessage(),
], 422);
}
return jsonApiResponseWithData($user, 201);
}
答案 0 :(得分:2)
我遇到了同样的错误,2小时后我意识到我错过了:
enctype="multipart/form-data" in the form
答案 1 :(得分:0)
删除此行(似乎您仍然不使用它):
->getClientOriginalExtension();
所以这应该起作用:
public function store(AvatarUploadRequest $request, UserService $userService) {
$user = $request->user();
try {
$file = $request->file('avatar');
$file = url("/avatars") . "/" . $user->uuid . ".jpg";
$destinationPath = "avatars";
$user->avatar = $request->file('avatar')->move($destinationPath, $file);
$user->avatar = $file;
$user->save();
$userService->updateAvatar($user, $file);
} catch (\Exception $e) {
return jsonApiResponse([
'avatar' => $e->getMessage(),
], 422);
}
return jsonApiResponseWithData($user, 201);
}
答案 2 :(得分:0)
你必须添加
enctype="multipart/form-data"
- 在表单中,因此您可以使用 extension() 之类的函数或
“哑剧:png、jpg、jpeg”