Jul 21, 2016
0
Level 1
Get file (image) controller not working
I'm learning to upload / manage files with Laravel and I used this tutorial : https://www.codetutorial.io/laravel-5-file-upload-storage-download/
I can upload file and display the name of the files but I can't display the images. The console doesn't return any error.
I tried to use Storage::disk('public') instead of Storage::disk('local') and I had the same problem (I also moved the images).
Thanks !
Route :
Route::get('fileentry/get/{filename}', [
'as' => 'getentry', 'uses' => 'FileEntryController@get']);
Controller :
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Fileentry;
use Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Http\Response;
class FileEntryController extends Controller {
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$entries = Fileentry::all();
return view('fileentries.index', compact('entries'));
/*
return view('fileentries.index');
*/
}
public function add() {
$file = Request::file('filefield');
$extension = $file->getClientOriginalExtension();
Storage::disk('local')->put($file->getFilename().'.'.$extension, File::get($file));
$entry = new Fileentry();
$entry->mime = $file->getClientMimeType();
$entry->original_filename = $file->getClientOriginalName();
$entry->filename = $file->getFilename().'.'.$extension;
$entry->save();
return redirect('fileentry');
}
public function get($filename){
$entry = Fileentry::where('filename', '=', $filename)->firstOrFail();
$file = Storage::disk('local')->get($entry->filename);
return (new Response($file, 200))
->header('Content-Type', $entry->mime);
}
}
Model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Fileentry extends Model
{
//
}
View :
@extends('layouts.app')
@section('content')
<form action="{{route('addentry', [])}}" method="post" enctype="multipart/form-data">
<input type="file" name="filefield">
<input type="submit">
</form>
<h1> Pictures list</h1>
<div class="row">
<ul class="thumbnails">
@foreach($entries as $entry)
<div class="col-md-2">
<div class="thumbnail">
<img src="{{route('getentry', $entry->filename)}}" alt="ALT NAME" class="img-responsive" />
<div class="caption">
<p>{{$entry->original_filename}}</p>
</div>
</div>
</div>
@endforeach
</ul>
</div>
@endsection
The url of the image (in the source code) is :
<img src="http://project-name.com/fileentry/get/php3153.tmp.jpg" alt="ALT NAME" class="img-responsive">
Please or to participate in this conversation.