首页 > 解决方案 > 在 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>

有人能指出我在这里做错了吗...

标签: laravel

解决方案


首先,您没有将附件的名称从您的视图传递回您的控制器,因此将您的视图更改为:

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

推荐阅读