【问题标题】:Upload images and showing them in a view Laravel 5.2上传图像并在视图中显示它们 Laravel 5.2
【发布时间】:2019-03-12 01:48:53
【问题描述】:

我做了一个上传一些产品图片的功能。当我遍历所有产品时,我也想显示图像。

问题是,图像正在上传,但是当我使用@foreach 迭代时无法呈现它。我尝试在控制器中获取路径,但没有成功。

到目前为止,我已经这样做了:

在 config/filesystems.php 我创建了一个自定义存储

'products' => [
        'driver' => 'local',
        'root'   => public_path('/pictures/uploads/products'),
    ],

当我创建新产品时:

<h1>Create new product</h1>
  {!! Form::open(['route' => 'vendor.allproducts', 'files'=>true]) !!}
  <div class="form-group">
     {!! Form::label('Title', 'Title:') !!}
     {!! Form::text('title',null,['class'=>'form-control']) !!}
  </div>
  <div class="form-group">
     {!! Form::label('File', 'File:') !!}
     {!! Form::file('image') !!}
  </div>

当我遍历我的产品信息时:

@foreach ($products as $product)
    <tr> 
      .
      .

       <td><img src="{{ $product->imagePath }}"></td>
     </tr>
 @endforeach

在控制器中:

public function store(){
    $product = Request::all();
    $file = Request::file('image');
    $extension = $file->getClientOriginalExtension();
    Storage::disk('products')->put($file->getFilename().'.'.$extension,  File::get($file));
    //$product->imagePath = Input::file('image')->getRealPath();
    Auth::user()->products()->create($product);
    return redirect()->route('allproducts');
}

【问题讨论】:

  • 为什么这个//$product-&gt;imagePath = Input::file('image')-&gt;getRealPath();被评论了?
  • 因为它不起作用。在 $product->imagePath 列中获取文件路径的尝试失败。

标签: php laravel file-upload laravel-5 image-uploading


【解决方案1】:

您的 Store 方法将是

if(input::hasfile("image")){
        $files = Input::file('image');
        $name = time()."_". $files->getClientOriginalName();
        $image = $files->move(public_path().'/image' , $name);
        $imagefile->image=$name;
    }
         $imagefile->save();

你的观点应该是这样的

<td><img src="{{URL::to('/image/' . $product->image)}}"></td>

【讨论】:

  • 感谢您的回答,很抱歉没有早点看到!它与我所做的不同,但它有效! @recovery men你能告诉我一种方法来修复变量中文件的路径,这样当我写&lt;img src="{{$product-&gt;image)}}"&gt;时,它会起作用吗?我尝试了 $destinationPath = public_path('/uploads/products/')$product['imagePath'] = '/uploads/products/' . $extension; 但我希望它更动态,例如:$product['imagePath'] = $destinationPath . $extension; 但这会返回 C:\xampp\htdocs\shop\public\/uploads/products/" 而不是 /uploads/products/image。 jpg
  • 它需要从创建时移动的路径获取图像,即使您也可以从存储方法更改路径以存储上传的图像。在上面的示例中,您的图像将存储在 public/images 文件夹中
猜你喜欢
  • 2017-02-17
  • 2017-07-16
  • 1970-01-01
  • 1970-01-01
  • 2017-06-02
  • 1970-01-01
  • 1970-01-01
  • 2017-05-28
  • 2011-05-07
相关资源
最近更新 更多