Get files with server path in application, not over http?

99封情书 提交于 2019-12-13 08:17:02

问题


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().



来源:https://stackoverflow.com/questions/53145005/get-files-with-server-path-in-application-not-over-http

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!