Laravel:下载的文件在某些​​浏览器中缺少扩展名

时间:2021-02-19 11:28:33

标签: php laravel

我有一个在 Firefox 和 Safari 上运行良好的文件下载功能,但是如果我尝试在 Chrome 或 MS Edge 上下载相同的文件,则下载的文件没有扩展名。

这是函数

public function download_chapter_file(Downloadable $downloadable, Request $request): StreamedResponse
    {
        if (!$request->hasValidSignature()) abort(401);
        $headers = ['Content-Type' => 'application/'.$downloadable->type];
        return Storage::download($downloadable->path,$downloadable->title,$headers);
    }

$downloadable->typeexcelpdf
$downloadable->path 是完整的文件路径。例如storage/app/public/downloadable/chapters/9/ycCjt0K911x3b1aFjX8i0S9Jj8.pdf
我试过使用 return response()->download(); 但它并没有解决问题。
感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

试试这个,它对我有用:-

$headers = array(
          'Content-Type: application/pdf',
        );

return Response::download($downloadable->path,$downloadable->title,$headers);

答案 1 :(得分:0)

经过数小时的试验。我终于找到了一个可行的解决方案。

use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;

class StorageController extends Controller
{
    public function download_chapter_file(Downloadable $downloadable, Request $request):StreamedResponse
    {
        if (!$request->hasValidSignature()) abort(401);
        $extension  = File::extension(storage_path('app/'. $downloadable->path));
        $filename = $downloadable->title.'.'.$extension;
        return Storage::download($downloadable->path,$filename);
    }
}

谢谢大家的尝试