无法阅读从Laravel 5中的BLOB转换回的PDF?

Roh*_*han 11 php pdf base64 laravel laravel-5

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

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

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);
}
Run Code Online (Sandbox Code Playgroud)

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

Ste*_* E. 1

标头可能返回不正确,这导致文件显示为不可读。

通过替换来强制它们:

header('Content-Description: File Transfer');
return response()->download($path);
Run Code Online (Sandbox Code Playgroud)

和:

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

return response()->download($path, $file->name, $headers);
Run Code Online (Sandbox Code Playgroud)