在应用程序中获取具有服务器路径的文件,而不是通过 http?

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

我为我的客户设置了上传区域,哪些文件应该是私有的,public 不可访问。由于非 public 可用性,我如何才能获得此文件以在应用程序中预览?有没有其他方法可以直接从服务器获取?

是的,您可以在不制作文件的情况下提供文件public。

基本思路是添加一个授权请求然后提供文件的路由。

例如:

Route::get('files/{file}', function () {
    // authorize the request here
    return response()->file();
});

有许多内置的文件服务方式。我推荐以下四个:

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

对于存储在支持临时 URLs 的外部系统(如 Amazon S3)中的文件,有时最好为文件生成 URL 而不是直接从您的应用程序提供。您通常可以使用 Storage::temporaryUrl().

如果您正在处理图像:

Route::get('/file/download', function() {
    // get your filepath
    $filepath = 'path/to/image/image.png';
    return Response::download($filepath);
});

那么在你看来:

<img src="{{url('/file/download')}}" class="rounded-circle" />

对于任何其他文件:

Route::get('/file/download', function() {
    // get your filepath
    $filepath = 'path/to/file/essay.docx';
    return Response::download($filepath);
});

您的看法:

<a href="{{url('/file/download/')}}">Download</a>

如果您愿意,可以使用控制器:

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);
    }
}

那么您的路由定义将如下所示:

Route::get('/file/download', ['as' => 'file.download', 'uses' => 'MyNamespace\FilesController@downloadFile']);

您的观点:

<a href="{{route('file.download')}}">Download</a>