如何使用 Laravel 10 允许用户在多个视图中下载文件?

问题描述 投票:0回答:1

假设我有一个 uploads.index.view.php 和一个 uploads.show.view.php,它们通向 UploadController,它是一个资源控制器。

索引视图显示用户上传的文件列表,如下所示:

上传控制器:

public function index() {
    return view('home', [
        'uploads' => Upload::paginate(20)
    ]);
}

索引视图:

@foreach ($uploads as $upload)
<tr>
    <td class="table-uploaded table-td--center"><a href="#">{{$upload->user->name}}</a></td>
    <td class="table-cat table-td--center">{{$upload->category->category}}</td>
    @if ($upload->name)
    <td class="table-title"><a href="{{route('uploads.show', $upload->id)}}">{{$upload->name}}</a></td>
    @else
    <td class="table-title"><a href="{{route('uploads.show', $upload->id)}}">{{$upload->title}}</a></td>
    @endif
</tr>
@endforeach

显示视图显示单个上传的页面,如下所示:

public function show(Upload $upload) {
    return view('single', [
        'upload' => $upload
    ]);
}

索引应包含

<a href="DOWNLOAD LINK HERE">UPLOAD TITLE</a>
,单个视图应包含
<a href="DOWNLOAD LINK HERE">Download</a>

点击两个链接中的任何一个后,让浏览器下载相应的

Eloquent
的最
$upload
方式是什么?我是在索引内部创建一个函数并在 UploadController 中显示公共函数,还是为 UploadController 创建一个单独的
public function download()

希望得到详细的答案,包括在

<a></a>
标签和路线中放入什么内容,因为我对此还很陌生。

laravel download laravel-10
1个回答
0
投票

你可以像这样简单地实现它:

路线:

Route::get('/uploads/{upload}/download', 'UploadController@download')->name('uploads.download');

UploadController中,添加下载方法。您可以使用 Laravel 的内置下载响应将文件提供给用户。

public function download(Upload $upload) {
    $filePath = storage_path('app/uploads/' . $upload->file_path);
    
    return response()->download($filePath, $upload->name);
}

将占位符“DOWNLOAD LINK HERE”替换为下载方法的实际路径:

<td class="table-title"><a href="{{ route('uploads.download', $upload->id) }}">{{$upload->name ?? $upload->title}}</a></td>

将占位符“DOWNLOAD LINK HERE”替换为下载方法的实际路径:

<a href="{{ route('uploads.download', $upload->id) }}">Download</a>
© www.soinside.com 2019 - 2024. All rights reserved.