我对 laravel 文件上传图片有疑问
Posted
技术标签:
【中文标题】我对 laravel 文件上传图片有疑问【英文标题】:i have problem with laravel fileupload image 【发布时间】:2022-01-05 12:28:57 【问题描述】:有人可以帮助我,我想添加带有图像的文章。图像已成功进入目录,但在数据库中名称始终为 D:\xampp\tmp\php......tmp。
我已将系统文件更改为公开。
控制器
public function store(Request $request)
//
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
if ($request->file('thumbnail'))
$imageName = time().'.'.$request->file('thumbnail')->getClientOriginalExtension();
$validatedData['thumbnail'] = $request->thumbnail->move(public_path('uploads/article/'), $imageName);
//dd($validateData['thumbnail']);
Article::create($validateData);
return redirect('/admin-article')->with('success', 'Data has been successfully added');
【问题讨论】:
您正在使用move()
方法,如果成功则返回 true,否则返回 false。所以基本上,您存储的是 $validatedData['thumbnail']
布尔值。我建议改用storeAs()
方法。它返回您需要的路径。
【参考方案1】:
试试这个
if ($request->file('thumbnail'))
$imageName = time().'.'.$request->file('thumbnail')->getClientOriginalExtension();
$request->thumbnail->move(public_path('uploads/article/'), $imageName);
$validatedData['thumbnail'] = url('uploads/article/'.$imageName);
它返回路径而不是 url 的原因是因为您使用的是 public_path 而不是 url()
【讨论】:
【参考方案2】:控制器代码
public function store(Request $request)
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
// Check if request has file
if($request->hasFile('thumbnail'))
// Get File
$file = $request->file('thumbnail');
// Get File Extention
$fileGetFileExtension = $file->getClientOriginalExtension();
// Create customized file name
$fileName = Str::random(20).'_'.date('d_m_Y_h_i_s').'.'.$fileGetFileExtension;
// Save File to your storage folder
Storage::disk('public')->put('uploads/article/'.$fileName,File::get($file));
else
$fileName = null;
$validatedData['thumbnail'] = $fileName;
Article::create($validateData);
return redirect('/admin-article')->with('success', 'Data has been successfully added');
运行php artisan storage:link
,如果没有创建
在刀片中,您可以像这样获取文件
<a href=" url('storage/uploads/article/'.$actical->thumbnail) "></a>
我希望这会有所帮助。 :D
【讨论】:
【参考方案3】:感谢您的回答我的问题已经用这样的代码解决了,但只有存储在数据库中的文件名而不是目录名。
public function store(Request $request)
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
$imageName = time().'.'.$request->thumbnail->getClientOriginalExtension();
$request->thumbnail->move(public_path('articles/'), $imageName);
$Article = new Article;
$Article->title = $validateData['title'];
$Article->thumbnail = $imageName;
$Article->slug = $validateData['slug'];
$Article->description = $validateData['description'];
$Article->save();
return redirect('/admin-article')->with('success', 'Data has been successfully added');
【讨论】:
以上是关于我对 laravel 文件上传图片有疑问的主要内容,如果未能解决你的问题,请参考以下文章