在我的vue js ajax帖子中存储文件,如
$imagename = sha1(time()).".".$request->profile_pic->extension();
$path = $request->profile_pic->storeAs('public/images/users',$imagename);
$user = \Auth::user();
//remove old file and retain new one
if(\Storage::has($user->profile_pic)){
\Storage::delete($user->profile_pic);
}
$user->picture = $path;
$user->save();
以上是有效的,图像保存在storage/app/public/images/users
中,这是可以的
但数据库字段保存为public/images/users
,因此在访问前端的值时找不到它
经过多次测试,我发现在数据库中我需要将文件保存为
storage/images/users //note path is not starting with public
所以我改变了
$user->picture="storage/images/users".$imagename;
但是现在执行此操作后,删除旧文件的部分将失败
if(\Storage::has($user->profile_pic)){
\Storage::delete($user->profile_pic);
}
如何调整删除部分也能正常工作。
更新完整控制器代码
public function changeProfilePic(Request $request){
if ($request->hasFile('profile_pic')) {
$imagename = sha1(time()).".".$request->profile_pic->extension();
$path = $request->profile_pic->storeAs('public/images/users',$imagename);
$user = \Auth::user();
//remove old file and retain new one
if(\Storage::has($user->profile_pic)){
\Storage::delete($user->profile_pic);
}
$user->profile_pic = "storage/images/users".$imagename;
//if save fails delete the uploaded image
if($user->save()){
return response("true", 200);
}else {
\Storage::delete($path);
return response("false", 200);
}
}else{
return response("false", 200);
}
}
在使用vue-image-crop-upload
插件
<image-uploader field="profile_pic"
...other stuff for plugin
url="/change-profile-picture"
langType="en"
:headers="headers"
img-format="png"></image-uploader>
laravel route
Route::post('/change-profile-picture', 'UserController@changeProfilePic');
答案 0 :(得分:1)
这是我解决它的方式
快速检查后,我发现无论我尝试什么
Storage::has or Storage::exists
Aways返回false并且`Storage :: delete不会抛出任何错误,即使文件不存在
同样快速检查文件路径我必须将存储在数据库中的名称从存储更改为公共,因此会爆炸和内爆
有效的最终代码是
public function changeProfilePic(Request $request){
if ($request->hasFile('profile_pic')) {
$imagename = sha1(time()).".".$request->profile_pic->extension();
$path = $request->profile_pic->storeAs('public/images/users',$imagename);
$user = \Auth::user();
$olduserpicdata = explode("/",$user->profile_pic);
$olduserpicdata[0] = "public";
//remove old file and retain new one
Storage::delete(implode("/",$olduserpicdata));
$user->profile_pic = "storage/images/users/".$imagename;
//if save fails delete the uploaded image
if($user->save()){
return response("true", 200);
}else {
Storage::delete($path);
return response("false", 200);
}
}else{
return response("false", 200);
}
}