Last updated on November 21, 2022
Create a controller called UploadController.php
with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class UploadController extends Controller
{
public function index()
{
$files = Storage::disk('s3')->files('files');
$data = [];
foreach($files as $file) {
$data[] = [
'name' => basename($file),
'downloadUrl' => url('/download/'.base64_encode($file)),
'removeUrl' => url('/remove/'.base64_encode($file)),
];
}
return view('upload', ['files' => $data]);
}
public function store(Request $request)
{
$this->validate($request, [
'file' => 'required|max:2048'
]);
if ($request->hasFile('file')) {
$file = $request->file('file');
$name = time() . $file->getClientOriginalName();
$filePath = 'files/' . $name;
Storage::disk('s3')->put($filePath, file_get_contents($file));
}
return back()->withSuccess('File uploaded successfully');
}
public function destroy($file)
{
$file = base64_decode($file);
Storage::disk('s3')->delete($file);
return back()->withSuccess('File was deleted successfully');
}
public function download($file)
{
$file = base64_decode($file);
$name = basename($file);
Storage::disk('s3')->download($file, $name);
return back()->withSuccess('File downloaded successfully');
}
}
Create a view file
Create a file called upload.blade.php in the resources/views directory with the below code.
<div class="row">
<h3>Upload File</h3>
<div class="card col-sm-12">
<form action="{{ url('/store') }}" method="POST" enctype="multipart/form-data" class="form-inline">
{{ csrf_field() }}
<div class="form-group">
<label for="file">Select File</label>
<input class="form-control-file" type="file" name="file" id="file">
</div>
<button type="submit" class="btn btn-primary mb-2">Upload</button>
</form>
</div>
</div>
<div class="row">
<h3>Files</h3>
<div class="card col-sm-12">
@if (count($files) > 0)
@foreach ($files as $file)
<a href="{{ url($file['downloadUrl']) }}">{{ $file['name'] }}</a>
<form action="{{ url($file['removeUrl']) }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit" class="btn btn-default">Remove</button>
</form>
@endforeach
@else
<p>Nothing found</p>
@endif
</div>
</div>
Define Routes
Open your routes/web.php directory and add the following route definitions to it.
Route::get('/', 'UploadController@index');
Route::post('/store', 'UploadController@store');
Route::get('download/{file}','UploadController@download');
Route::delete('remove/{file}','UploadController@destroy');