I have upload area for my customers which files should be private and not public accessible. Because of non-public availability, how can I get this files for preview in application? Is there any other way to get it directly from server?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
If you are working with images:
Route::get('/file/download', function() {
// get your filepath
$filepath = 'path/to/image/image.png';
return Response::download($filepath);
});
Then in your view:
<img src="{{url('/file/download')}}" class="rounded-circle" />
For any other file:
Route::get('/file/download', function() {
// get your filepath
$filepath = 'path/to/file/essay.docx';
return Response::download($filepath);
});
Your view:
<a href="{{url('/file/download/')}}">Download</a>
If you wish you may use a controller:
namespace MyNamespace;
use Illuminate\Routing\Controller;
class FilesController extends Controller
{
public function downloadFile()
{
// get your filepath
$filepath = 'path/to/file/essay.docx';
return Response::download($filepath);
}
}
Then your route definition would look like:
Route::get('/file/download', ['as' => 'file.download', 'uses' => 'MyNamespace\FilesController@downloadFile']);
And your view:
<a href="{{route('file.download')}}">Download</a>
回答2:
Yes, you can serve files without making them public.
The basic idea is that you add a route which authorizes the request and then serves the file.
For example:
Route::get('files/{file}', function () {
// authorize the request here
return response()->file();
});
There are many built-in ways for serving files. Here are four that I would recommend looking at:
// For files on the local filesystem:
response()->file()
response()->download()
// For files that may be in an external storage system (SFTP, etc.)
Storage::response()
Storage::download()
For files stored in an external system (like Amazon S3) that supports temporary URLs, it's sometimes better to generate a URL to the file instead of serving it directly from your application. You can usually do this with Storage::temporaryUrl()
.