php - 无法在 Laravel 5 中读取从 BLOB 转换回的 PDF?

标签 php laravel pdf laravel-5 base64

我正在尝试使用 BLOB 将文件保存在数据库中。我知道这不是一个很好的做法,但需要这样做。

无论如何,我面临的问题是返回的 PDF 文件不再可读。但是所有其他文件,如 docx、odt、txt、jpg 等,在从 blob 转换回来时都工作正常。

public function store(Request $request)
{
    $data = $request->all();

    $file = $request->file('file');

    $data['data'] = base64_encode(file_get_contents($file));
    $data['extension'] = $file->guessExtension();
    $data['name'] = $file->getClientOriginalName();

    $file = $this->fileRepo->create($data);

    return jsend()->success()
                  ->message("Resource Created Successfully")
                  ->data($file->toArray())
                  ->get();
}

public function download($id)
{
    $file = $this->fileRepo->find($id);

    $randomDir = md5(time() . $file->id . $file->user->id . str_random());

    mkdir(public_path() . '/files/' . $randomDir);

    $path = public_path() . '/files/' . $randomDir . '/' . html_entity_decode($file->name);

    file_put_contents($path, base64_decode($file->data));

    header('Content-Description: File Transfer');

    return response()->download($path);
}

我哪里出错了,有没有一种特殊的方法可以将 PDF 存储在 blob 字段中?

最佳答案

可能是错误地返回了 header ,这导致文件看起来不可读。

通过替换强制他们:

header('Content-Description: File Transfer');
return response()->download($path);

与:

$headers = array(
   'Content-Description: File Transfer',
   'Content-Type: application/octet-stream',
   'Content-Disposition: attachment; filename="' . $file->name . '"',
   );

return response()->download($path, $file->name, $headers);

关于php - 无法在 Laravel 5 中读取从 BLOB 转换回的 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33866052/

相关文章:

css - laravel 5.3.16 不包括 Bootstrap 功能?

php - 如何将两个变量传递给 View ?

c++ - 有没有用 C++ 编写的开源 PDF 打印机?

php - Wordpress Posts 奇数/偶数 Li 布局

php - 如何将 Paytm 与 Codeigniter 集成

mysql - 尝试更新数据库中的列但 NOT NULL 属性不允许我更新值。我正在使用 Laravel

c# - 使用 hiqpdf 将带有图像的 HTML 转为 PDF

pdf - 如何使用 `pdftk` 指定附件的描述?

php - 拉拉维尔 : How to create dynamic functions (methods) (using foreach loop) in class

PHP:等效于使用 eval 包含