无法从laravel中的存储目录中获取图像

时间:2018-06-01 07:09:23

标签: laravel image laravel-blade

当我在索引页面中显示图像时,不显示图像。

我的视图文件(index.blade.php):

<div class="row">
    @if(App\News::count() > 0)
      @foreach($news as $n)
        <div class="col-md-8 panel border-right">
          <br />
          <img src="{{ asset('storage/images/news/'. $n->image) }}" width="200px" height="100px">
 --$n->image returns News_1.jpg which is the image name stored in the storage directory.
          <h1>First Div</h1>
        </div>
      @endforeach
   @endif
       <div class="col-md-4">
         <h1>Second Div</h1>
       </div>
</div>  

我的控制器:

    public function store(Request $request)
{

    $this->validate($request, 
    [

        'head' => 'required|max:191',
        'title' => 'required|max:191',
        'body' => 'required',
        'pic' => 'required'

    ]);
    $filename="";
    $extension="";

    if($request->hasFile('pic'))
    {

        if((News::orderBy('id', 'desc')->first()) != null)
        {
            $id = ((News::orderBy('id', 'desc')->first()->id)+1);
            $filename = "News_" . $id;
        }
        else
        {
            $filename = "News_" . 1;
        }
        $extension = $request->pic->getClientOriginalExtension();
        $filename = $filename . "." . $extension;

        //return $request->pic->getClientOriginalName();
        $request->pic->storeAs('public/images/news', $filename);


    }
    else
    {
        return redirect()->back()->withInput(Input::all())->withErrors(['message' => 'Please select a valid file.']);
    }

    $news = new News;
    $news->head = $request->head;
    $news->title = $request->title;
    $news->body = $request->body;
    $news->image = $filename;

    $news->save();

    Session::flash('success', 'The record was successfully saved.');

    return redirect()->route('news.index');


}  

我已将存储目录与公共目录相关联:
storage_link

我的目录结构:
directory_structure

图像存储在应用程序和数据库中,但无法正常显示,当我运行应用程序时,我得到以下视图:
view

在新标签页中打开图片时,我会看到以下地址栏:
address

这是本地驱动程序配置:

local diriver

提前感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

如果您当前的路线是/板球,并使用&#39; storage / images / news / news1.jpg&#39;来引用图像。那么网络浏览器将假设这个图像是相对于板球资源的。

你的图片src需要以完整的URL或/开头,以表明它是相对于根文件夹的

在这种情况下,我会对URL进行硬编码,因为无论如何你已经在资产助手中对其进行了硬编码

<img src="/storage/images/news/{{ $n->image }}" 

答案 1 :(得分:-1)

您可以尝试将本地驱动程序设置为以下内容:

'public' => [
    'driver' => 'local',
    'root' => storage_path('app/public'),
    'url' => env('APP_URL').'/storage',
    'visibility' => 'public',
],