Ref:https://www.codetutorial.io/laravel-5-file-upload-storage-download/
php artisan make:migration create_fileentries_table --create="fileentries"
create_fileentries_table.php1 2 3
| $table->string('filename'); $table->string('mime'); $table->string('original_filename');
|
php artisan migrate
php artisan make:model Fileentry
routes.php1 2 3
| Route::get('fileentry', 'FileEntryController@index'); Route::get('fileentry/get/{filename}', [ 'as' => 'getentry', 'uses' => 'FileEntryController@get']); Route::post('fileentry/add',[ 'as' => 'addentry', 'uses' => 'FileEntryController@add']);
|
php artisan make:controller FileEntryController
FileEntryController.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| use Storage; use File; use Fileentry; public function index() { $entries = Fileentry::all(); return view('fileentries.index', compact('entries')); } public function add(Request $request) { $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'); }
|
fileentries/index.blade.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| @extends('layouts.app') @section('content') <form action="fileentry/add" method="post" enctype="multipart/form-data"> {{ csrf_field() }} <input type="file" name="filefield"> <input type="submit"> </form> <h1> Pictures list</h1> <div class="row"> <ul> @foreach($entries as $entry) <li>{{$entry->filename}}</li> @endforeach </ul> </div> @endsection
|
Test Upload Now
Display
FileEntryController.php1 2 3 4 5 6 7 8
| public function get($filename){ $entry = Fileentry::where('filename', '=', $filename)->firstOrFail(); $file = Storage::disk('local')->get($entry->filename); return response($file, 200)->header('Content-Type', $entry->mime); //太舊不能用了return (new Response($file, 200))->header('Content-Type', $entry->mime); }
|
Full index
fileentries/index.blade.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| @extends('layouts.app') @section('content') <form action="{{route('addentry', [])}}" method="post" enctype="multipart/form-data"> {{ csrf_field() }} <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
|