【问题标题】:Return Binary Image Data from Laravel with Correct Content Type从 Laravel 返回具有正确内容类型的二进制图像数据
【发布时间】:2021-12-10 09:45:58
【问题描述】:

我有一个 Laravel 控制器,它从数据库或 API 等来源检索二进制图像数据并将其作为响应返回:

class ExampleController extends Controller 
{

  // ...

  public function testImage(Request $request)
  {
    // This is a binary string not a stream or file handle
    $binaryImageData = $this->repository->getImage($request->query);

    return response($binaryImageData);
  }
}

但是,当我在浏览器中打开它时,Laravel 返回一个 Content-Type 标头值“text/html”,因此二进制数据被呈现为 HTML。

我不能保证我可以访问图像数据的正确内容类型。

那么我将如何检测并返回正确的类型?

【问题讨论】:

    标签: php laravel http response mime


    【解决方案1】:

    我认为这些方法可以提供帮助:

    mb_detect_encoding

    (检测字符编码。)

    $encoding = mb_detect_encoding($binaryImageData, mb_list_encodings(), true);
    

    Symfony\Component\HttpFoundation\File\UploadedFile::getClientMimeType

    (返回文件 mime 类型。)

    $mimetype = $binaryImageData->getClientMimeType();
    

    使用内容类型 ($mimetype) 的响应标头示例:

          return response(Storage::get($file->path))
            ->withHeaders([
              'Content-disposition' => 'attachment; filename=' . $file->file_name,
              'Access-Control-Expose-Headers' => 'Content-Disposition',
              'Content-Type' => $file->mimetype,
            ]);
    

    【讨论】:

    • 这行不通。 $binaryImageData 是一个包含二进制数据的字符串,它没有任何方法。 getClientMimeType 似乎是UploadedFile 的一种方法。需要明确的是,没有文件正在上传。我也不明白你为什么要检测二进制字符串的字符编码,无论mb_detect_encoding 检测到什么肯定是错误的,因为它是二进制而不是文本。我已经在我的问题中的代码中添加了注释,因为它显然不够清楚。
    【解决方案2】:

    经过进一步研究,我确定没有特定于 Laravel 的方法来检测二进制字符串的 mime 类型。但是有一个通用的 PHP 方式:

    function detectMimeType(string $input)
    {
        return (new finfo(FILEINFO_MIME_TYPE))->buffer($input);
    }
    

    Laravel 目前还拥有 league/filesystem 作为依赖项,而 league/mime-type-detection 提供了它自己的基于类的 finfo 包装器。我会推荐给任何喜欢 league/mime-type-detection 的人在他们的项目 composer.json 文件中明确要求它,以防 Laravel 将来放弃要求。

    【讨论】:

      猜你喜欢
      • 2018-03-16
      • 2018-11-23
      • 2013-01-23
      • 2015-02-25
      • 1970-01-01
      • 2021-06-16
      • 2011-03-19
      • 1970-01-01
      相关资源
      最近更新 更多