Подтвердить что ты не робот

Не удается прочитать PDF, преобразованный обратно из BLOB в Laravel 5?

Я пытаюсь сохранить файлы в БД с помощью 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?

4b9b3361

Ответ 1

Возможно, что заголовки возвращаются неправильно, и это приводит к тому, что файл становится нечитаемым.

Извлеките их, заменив:

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

Ответ 2

Вы можете настроить возврат заголовка таким образом. вам нужно использовать ответ Laravel, т.е.

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