从存储文件夹下载的 Laravel 文件已损坏

问题描述 投票:0回答:4

我尝试从存储文件夹下载 jpg/png 图像,但下载后该图像已损坏。 这是我的控制器

public function download($filename) {

    $headers = array(
        'Content-Type: image/png',
    );
    return response()->download(storage_path() . '/'.$filename, 'final.png', $headers);

}

打开后是这样的

即使我使用核心 php 脚本下载仍然面临同样的问题。

php laravel laravel-5
4个回答
28
投票

我相信 Laravel 框架可能会引入空格,这可能会破坏 header() 函数。

在第一次 header() 调用之前使用 ob_end_clean() 来删除任何额外的空格。


13
投票

像这样之前添加这个方法

ob_end_clean();
$headers = array(
    'Content-Type: image/png',
);
return response()->download(storage_path() . '/'.$filename, 'final.png', $headers);

!享受


0
投票

After Download .jpg,png,gif and .xlsx 是的 !它的工作; 我读了这个问题15天,终于得到了解决方案

  • Larabel 5.8 和 PHP 7.3

public function download_user_photo($id) {
    ob_end_clean();
    $photo = UserGallery::find($id);
    $path = 'storage/users/'.$photo->image_url;
    enter code here
        if (\File::exists($path)) {
            return response()->download($path);
            } else {
                return redirect()->back()->with('danger', 'Image does not exist.');
        }
    }


0
投票

这也解决了我的问题

ob_end_clean();
        $headers = [
            'Content-type' => 'application/zip',
            'Content-Disposition' => "attachment; filename='$name.zip'",
            'Cache-Control'=>'private'
        ];

通过在 headers 数组之前添加

ob_end_clean();
,我能够下载我的 zip 文件,而不会出现任何损坏!

© www.soinside.com 2019 - 2024. All rights reserved.