doubao6681 2017-09-13 13:07
浏览 41

如何为下载的文件Laravel 5.0指定扩展名

I am attempting to download a file when the user hits a route, and I was able to do so. However, when the user wants to download a docx or doc file, the file extension doesn't have .doc in it. To better ask my question, my code is below:

Route::get('resumeDownload', function() {
    $user = Auth::user();
    $path = $user->cv()->first()->path; //when the user uploads a document, i store
    //the path of it in the database
    $extension = explode(".", $path)[1]; //if the user uploaded a doc, returns .doc etc
    $uploaded = Storage::get($path); //I get it from my storage
    return (new \Illuminate\Http\Response($uploaded, 200))
           ->header('Content-Type', 'application/pdf');
});

This code works great when the user wants to download a pdf, however for a .doc file or a .docx file, the file which is downloaded has no extension. I also save the extension and can easily retrieve it, if that could help. Is there anyway to make this work for .doc, .docx, .pdf, and .txt?

  • 写回答

1条回答 默认 最新

  • dongzhang7961 2017-09-13 13:22
    关注

    You can use the Content-Disposition header to specify the name of the downloaded file but there is no need to manually create the download response. Laravel already has a built int function to generate a download response with the proper Content-Disposition header

    $headers = ['Content-Type' => 'application/pdf'];
    return response()->download($fileContent, 'filename.pdf', $headers);
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度