laravel - 在 laravel 中下载文件
问题描述
我是 Laravel 的新手,我试图捕获存储在名为“Infrastructure”的数据库表中的文件名,以便为用户创建一个链接以下载该文件。下载有效,但我总是将错误的文件存储在目录中。
所以在我的名为 infrastructureController.php 的控制器中,我有这些代码。
public function show($id)
{
$infrastructure = $this->infrastructureRepository->find($id);
$Attachment = $infrastructure->inf_file; // captured filename in the database
if (empty($infrastructure)) {
Flash::error('Infrastructure not found');
return redirect(route('infrastructures.index'));
}
return view('infrastructures.show')->with('infrastructure', $infrastructure);
}
在我的路线或 web.php
我有这些代码...
Route::get('/download', function(){
$name = $Attachment;
$file = storage_path()."/app/public/infrastructure/".$Attachment;
$headers = array(
'Content-Type: application/pdf',
);
return Response::download($file, $name, $headers);
});
最后,在我的视图文件中,我有这个
<!-- Inf File Field -->
<div class="form-group">
{!! Form::label('inf_file', 'Attachements:') !!}
<a href="/download">Download Now</a>
</div>
有人能指出我在这里做错了吗...
解决方案
首先,您没有将附件的名称从您的视图传递回您的控制器,因此将您的视图更改为:
<!-- Inf File Field -->
<div class="form-group">
{!! Form::label('inf_file', 'Attachements:') !!}
<a href="/download/{{ $infrastructure->inf_file }}">Download Now</a>
</div>
然后在您的路线中,您需要像这样访问文件的名称:
Route::get('/download/{Attachment}', function($Attachment){
$name = $Attachment;
$file = Storage::disk('public')->get("infrastructure/".$Attachment);
$headers = array(
'Content-Type: application/pdf',
);
return Response::download($file, $name, $headers);
});
推荐阅读
- swift - 在 ViewController 中调用自动播放视频的控制器
- gdb - gdb 命令列表 - 第一次命中断点时,不调用命令
- algorithm - 如何正确重构基于案例的嵌套循环?
- go - 已声明但未使用
- javascript - 淡出错误/递减实现
- python - Google 学者使用 Captcha 阻止 python scrapy
- c - 组件 IA32 中的符号扩展
- android - 大家好,你能帮我解决一个问题,当从 json 删除、添加或更新数据时,我的 recyclerview 应该自动更新
- javascript - ReactJs 中带有承诺和状态变量的无限循环
- python - Writing with Python Greek letters to (Oracle) SQL file doesn't work