【问题标题】:Laravel - How to download sample Excel file from the storage [duplicate]Laravel - 如何从存储中下载示例 Excel 文件 [重复]
【发布时间】:2020-01-05 13:14:52
【问题描述】:

我在 Laravel-5.8 中有使用 Maatwebsite 包的 Excel 导入项目。我已经能够执行 Excel 导入并成功将其保存到数据库中。

用户控制器

class UserssController extends Controller
{
  public function importExportView()
  {
     return view('import');
  }

  public function import() 
  {
    Excel::import(new UsersImport,request()->file('file'));
    return back();
  }
}

user.blade

<div class="container">
    <div class="card bg-light mt-3">
        <div class="card-header">
            Import Excel
        </div>
        <div class="card-body">
            <form action="{{ route('import') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <input type="file" name="file" class="form-control">
                <br>
                <button class="btn btn-success">Import User Data</button>
            </form>
        </div>
    </div>

但是,还有一件事。我有一个示例 Excel 文件。在导入之前,我希望用户下载示例 excel 表,看看文件格式如何,以及应该如何排列。

文件在这个目录下:public/storage/sample/user.xlsx

如何修改我的代码,尤其是在视图中实现这一点?

谢谢。

【问题讨论】:

  • @nakov - 是的,谢谢

标签: laravel maatwebsite-excel


【解决方案1】:

storage 类中有一个download 方法可以帮助你

Storage::download('file.jpg');

您可以在docs查看更多信息

【讨论】:

    【解决方案2】:

    如果要直接在一个路由函数中下载,可以直接在return语句中使用response()-&gt;download()方法。

    有一个用这种方法下载文件的小例子

    /**
     * Download file with "response()->download()" method
     * @param Request $request
     * @param String  $filename containing filename and extension (.xls in this example)
     * @return BinaryFileResponse
     */
    public function downloadAction(Request $request, $pathHash, $filename) {
        // Get path from storage directory
        $path = storage_path('app/' . $filename);
    
        // Download file with custom headers
        return response()->download($path, $filename, [
            'Content-Type' => 'application/vnd.ms-excel',
            'Content-Disposition' => 'inline; filename="' . $filename . '"'
        ]);
    }
    

    此方法适用于public/storage 目录中不可用的所有文件。

    您可以通过文件的相应 mime 类型更改 Content-Type 标头值。这里有一张常用文件扩展名表:https://developer.mozilla.org/fr/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      • 2019-10-25
      • 2017-08-16
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多