【问题标题】:The image cannot be displayed because it contains errors laravel图片无法显示,因为它包含错误 laravel
【发布时间】:2020-03-23 00:52:03
【问题描述】:

我正在开发一个 laravel 项目,在该项目中我试图使用 url 显示图像,但得到了 error。我已经尝试了很多并搜索了所有内容,但我不明白为什么会出现此错误。我正在使用下面的函数

    public function displayImage($filename){

        $path = storage_path("app/taskImage/".$filename);

        if (!File::exists($path)) {
            abort(404);
        }

        $file = File::get($path);

        $type = File::mimeType($path);

        $response = \Response::make($file, 200);

        $response->header("Content-Type", $type);

        return $response;
    }

路线

Route::get('taskImg/{filename?}', [
        'uses' => 'FormController@displayImage',
    ]);

而我正在寻找的 URL 就像

http://localhost/project_name/public/taskImg/test.jpg

当我打印一些东西时,我得到了那个但没有得到图像。它显示一个带有错误消息的空白屏幕 The image cannot be displayed because it contains errors

【问题讨论】:

  • 下载该文件,并尝试在 gfx 应用程序中打开/加载以查看。然后在任何 text 编辑器中查看文件内容,看是否没有被 i 污染。 E. 通知
  • 我有 2 个问题 1. 你是在单个文件中还是在所有文件中出错 2. 你得到的确切网址是什么
  • 我已经从谷歌浏览器下载了文件并将其粘贴到我的目录中,所以我认为图像没有损坏。我对屏幕截图、移动图像和上传的文件做了同样的事情,但遇到了同样的问题。
  • @ShaielndraGupta,我对所有图像都得到了相同的结果,例如屏幕截图、从相机捕获、下载的图像。所有人都一样 无法显示图像“localhost/project_name/public/taskImg/test.jpg”,因为它包含错误。
  • 将此网址粘贴到您的 chrome 中并查看图像是否加载并让我知道此响应

标签: laravel laravel-5.7


【解决方案1】:

我花了很多时间寻找解决方案,我终于找到了!只需在返回响应之前添加ob_end_clean,如下所示:

ob_end_clean();
        return response()->file($path,['Content-type' => 'image/jpeg']);

我无法解释,因为我不知道发生了什么,任何人都可以解释一下吗?

【讨论】:

    【解决方案2】:

    你可以这样做

    $storagePath = storage_path("app/taskImage/".$filename);
    
    return Image::make($storagePath)->response();
    

    【讨论】:

    • 获取此 Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR) Class 'Image' not found
    • 在使用这个类之前,你必须将它包含在类声明之上的 use 语句中
    • 我知道并且我正在使用 return \Image::make($storagePath)->response();
    • 我对其他项目的 aws 服务器也做了同样的事情。但我不明白为什么它不能在本地主机上工作的确切问题
    • 我想知道你的图片存储在公共目录还是存储目录的项目中?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    相关资源
    最近更新 更多