Get files with server path in application, not ove

2019-09-20 01:49发布

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?

2条回答
冷血范
2楼-- · 2019-09-20 02:03

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>
查看更多
神经病院院长
3楼-- · 2019-09-20 02:14

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

查看更多
登录 后发表回答