我已成功将从用户上传的图像保存到“广告”表中名为“图像”的字段中。但是我在查看(blade.php)文件中显示图像时遇到问题。
我尝试在线搜索解决方案,但没有一个适用于我的解决方案...
以下是我的AdvertisementsController的存储方法:-
public function store(Request $request)
{
// $media = Media::all();
request()->validate([
'image' => 'required',
'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
//find current admin's id
$admin_user = auth()->id();
if ($request->hasFile('image')) {
$image = $request->file('image');
$image_name = str_slug($request->title).'.'.$image->getClientOriginalExtension();
$folderPath = public_path('/uploads/images');
$imagePath = $folderPath. "/". $image_name;
$image->move($folderPath, $image_name);
}
$title = request('title');
$description = request('description');
$sort_num = request('sort_num');
$media = Media::create([
'title' => $title,
'description' => $description,
'sort' => $sort_num,
'created_by' => $admin_user,
]);
Advertisement::create([
'image' => $imagePath,
'expired_at' => Carbon::now()->format('Y-m-d H:i:s'),
'media_id' => $media->id,
]);
// return back()->with('success', 'Your advertisement has been successfully created!');
return redirect('/advertisements');
}
我可以成功保存路径,但是保存的路径很长,例如:“ / Users / hannzern / Desktop / numericledger-backend / public / uploads / images / klang-river.jpeg”,并认为该路径将保存为“ /public/uploads/images/klang-river.jpeg”。这可能是问题吗?
以下是我的视图(blade.php)的代码:-
<h1>Advertisements</h1>
<ul>
@foreach ($advertisements as $advertisement)
<a href="/advertisements/{{$advertisement->id}}">
{{ $advertisement->media->title }}
</a>
<br>
//Three methods of retrieving the image from the path but all three not working
<img src="{{ $advertisement->image }}" height="300" width="200">
<img src="/Users/hannzern/Desktop/numericledger-backend/public/uploads/images/klang-river.jpeg" height="300" width="200">
<img src="/public/uploads/images/klang-river.jpeg" height="300" width="200">
<br>
<br>
<br>
<br>
@endforeach
</ul>
<a href="/advertisements/create">Add new advertisement</a>
另外,从文件目录中,我可以在/ public / uploads / images文件夹中看到“ klang-river.jpeg”图像。有人知道为什么吗? :(
答案 0 :(得分:2)
/public
将通过在浏览器的链接中使用/
来解决,因此您的链接应另存为数据库:
/Users/hannzern/Desktop/numericledger-backend/uploads/images/klang-river.jpeg
但是,要确保在托管应用程序的任何地方都可以使用此方法,则不应保存绝对路径。只将以下内容保存到数据库中:
klang-river.jpeg
然后,使用asset()帮助器,可以在模板中调用正确的网址:
<img src="{{ asset('uploads/images/' . $advertisement->image) }}" height="300" width="200">
这将解析为预期的URL。我希望这会有所帮助。