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

Php 无法读取从Laravel 5中的BLOB转换回的PDF?,php,laravel,pdf,laravel-5,base64,Php,Laravel,Pdf,Laravel 5,Base64,我正在尝试使用BLOB在DB中保存文件。我知道这不是一个很好的做法,但需要这样做 无论如何,我面临的问题是返回的PDF文件不再可读。但是,当从blob转换回来时,所有其他文件(如docx、odt、txt、jpg等)都可以正常工作 public function store(Request $request) { $data = $request->all(); $file = $request->file('file'); $data['data'] =

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

无论如何,我面临的问题是返回的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);
}

哪里出了问题?是否有特殊的方法将PDF存储在blob字段中?

可能返回的头不正确,这会导致文件看起来不可读

通过替换以下内容强制执行:

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);

你可以这样设置你的报头。你需要用拉威尔的回答

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));

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

也许这些评论会有帮助?据我所知,那个家伙是用第三方库把它编码成72行来解决的,但我不知道在我的应用程序中如何做到这一点。如何在php中使用一定长度的行对base64中的文件进行编码?上传和下载之前的文件有多大不同?类似于
diff before.pdf after.pdf
@AlexBlex是的,这两个文件有很大的不同。Git没有太多表现。上面写着
索引1e5308a..a6a4f0b 100644
,我不知道这是什么意思。但我查看了文件,返回的文件大小为786.4KB,无论最初是2MB还是3MB。但是phpmyadmin显示所有2/3MB都已存储。所以我猜当文件从数据库中返回时,不知何故有些文件被撕破了?@Rohan,你确定它是一个BLOB吗?AFAIK Mysql的blob限制为64kB。