Laravel无法显示上传的图像

Laravel无法显示上传的图像

问题描述:

I am attempting to create a simple file upload system for images, and even after hours of googling, I just can't seem to get it working. Users upload images to my website, I store the path of the image in the database, and then I show the images by making the database path the src of an img tag. Seems simple enough, but it still does not work for me. Anyway, here is my code.

//posting upload in controller
//i named images docs

public function postUpload(){

    Input::file('file')->move(base_path() . '/public/uploads');

    $doc = new Doc();
    $doc->title = Input::get('title');
    $doc->caption = Input::get('caption');
    $doc->path = base_path() . '/public/uploads' . Input::file('file')->getClientOriginalName();

    $doc->save();

}

And here is my index view where I display uploaded images:

@extends('layouts.caselistlayout');

@section('content')


@foreach($docs as $doc)
<h1>{{ $doc->title }}</h1>
<h2>{{ $doc->caption}}</h2>
<img src='{{ $doc->path }}'>

@endforeach

@stop

I can provide the code for my upload view, but I don't think it is needed in this situation.

Thanks for the help!

Edit: Forgot to mention that the exact problem is the images aren't displayed. The title and caption are displayed on the index page, but the image is not displayed. I only see the default HTML placeholder for where the image should be.

Edit 2: File ends up in the folder, and I can see the URL in the path column of the database.

我正在尝试为图像创建一个简单的文件上传系统,即使经过数小时的谷歌搜索,我也可以' 似乎让它运作起来。 用户将图像上传到我的网站,我将图像的路径存储在数据库中,然后通过使数据库路径成为img标记的src来显示图像。 看起来很简单,但它仍然不适合我。 无论如何,这是我的代码。 p>

  //在控制器中发布上传
 // i命名图像docs 
 
public function postUpload(){
 
输入:  :file('file') - &gt; move(base_path()。'/ public / uploads'); 
 
 $ doc = new Doc(); 
 $ doc-&gt; title = Input :: get(  'title'); 
 $ doc-&gt; caption = Input :: get('caption'); 
 $ doc-&gt; path = base_path()。  '/ public / uploads'。  Input :: file('file') - &gt; getClientOriginalName(); 
 
 $ doc-&gt; save(); 
 
} 
  code>  pre> 
 
 

这是我的索引视图,我显示上传的图像: p>

  @extends('layouts.caselistlayout'); 
 
 @ section('content')
  
 
 @ foreach($ docs as $ doc)
&lt; h1&gt; {{$ doc-&gt; title}}&lt; / h1&gt; 
&lt; h2&gt; {{$ doc-&gt; caption}}&lt;  / h2&gt; 
&lt; img src ='{{$ doc-&gt; path}}'&gt; 
 
 @ endforeach 
 
 @ stop 
  code>  pre> 
 
 我可以为我的上传视图提供代码,但我不认为在这种情况下需要它。 p> 
 
 

感谢您的帮助! p>

编辑2:文件最终在文件夹中,我可以在数据库的路径列中看到URL。 / p> div>

You are saving full physical path to the database which is causing the issue. You actually need a http address. Example:

http://example.com/uploads/img1.jpg

Remove the following line:

  $doc->path = base_path() . '/public/uploads' . Input::file('file')->getClientOriginalName();

Instead, save the following:

  $doc->path = 'uploads/' . Input::file('file')->getClientOriginalName();

and from your view:

<img src='{{ asset($doc->path) }}'>