Laravel应用程序中有一个功能,允许用户将个人资料图片上传到他们的个人资料。
这是方法:
/**
* Store a user's profile picture
*
* @param Request $request
* @return void
*/
public function storeProfilePicture(User $user = null, Request $request)
{
$user = $user ?? auth()->user();
//Retrieve all files
$file = $request->file('file');
//Retrieve the file paths where the files should be moved in to.
$file_path = "images/profile-pictures/" . $user->username;
//Get the file extension
$file_extension = $file->getClientOriginalExtension();
//Generate a random file name
$file_name = Str::random(16) . "." . $file_extension;
//Delete existing pictures from the user's profile picture folder
Storage::disk('public')->deleteDirectory($file_path);
//Move image to the correct path
$path = Storage::disk('public')->putFile($file_path, $file);
// Resize the profile picture
$thumbnail = Image::make($path)->resize(50, 50, function ($constraint) {
$constraint->aspectRatio();
});
$thumbnail->save();
$user->profile()->update([
'display_picture' => Storage::url($path)
]);
return response()->json(['success' => $file_name]);
}
我正在尝试使用干预图像库来调整存储文件夹中上传的图片的大小,但是我总是遇到相同的错误。
"Image source not readable", exception: "Intervention\Image\Exception\NotReadableException"
我也尝试过Storage::url($path)
和storage_path($path)
答案 0 :(得分:0)
下面的代码与存储路径配合得很好,您可以直接根据请求制作缩略图,并按如下所示放置到所需的路径中。 请注意,在这里,我并不是要删除预先存储的文件或目录,因为我假设这已经完成。
$file = $request->file('file');
$path = "public/images/profile-pictures/{$user->username}/";
$file_extension = $file->getClientOriginalExtension();
$file_name = time(). "." . $file_extension;
// Resize the profile picture
$thumbnail = Image::make($file)->resize(50, 50)->encode($file_ext);
$is_uploaded = Storage::put( $path .$file_name , (string)$thumbnail ); // returns true if file uploaded
if($is_uploaded){
$user->profile()->update([
'display_picture'=> $path .$file_name
]);
return response()->json(['success' => $file_name]);
}
快乐编码