[英]Can't open file downloaded via response()->download()
我有一種負責下載文件的方法。
$attachment = KnowledgeDatabaseAttachments::where('id', $id)->first();
if ($attachment) {
$filesPath = storage_path('app/knowledge_database_attachments');
return response()->download($filesPath . '/' . $attachment->physical_name);
}
下載后,當我嘗試打開它時(這是我的操作系統發出的錯誤消息):
Could not load image '88ebb9c0-11af-11e8-b056-b1568dc848cb.jpg'.
Error interpreting JPEG image file (Not a JPEG file: starts with 0x0a 0xff)
文件保存如下:
$filesPath = storage_path('app/knowledge_database_attachments');
$physicalName = Uuid::generate() . '.' . $file->getClientOriginalExtension();
$file->move($filesPath, $physicalName);
KnowledgeDatabaseAttachments::create([
'knowledge_database_id' => $page->id,
'name' => $file->getClientOriginalName(),
'physical_name' => $physicalName
]);
該目錄中存在文件,並且下載的文件具有正確的大小和名稱。
有趣的是,我還可以創建一個包含此文件的新聞通訊。 當我創建時事通訊文件被復制時:
$extension = explode('.', $attachment->physical_name)[1];
$newPhysicalName = Uuid::generate() . '.' . $extension;
File::copy($attachment->getPathAttribute(), $storagePath . DIRECTORY_SEPARATOR . $newPhysicalName);
SendMailAttachments::create([
'mail_id' => $mail->id,
'filename' => $attachment->name,
'physical_name' => $newPhysicalName,
]);
然后,在通訊編輯視圖中,我也可以使用以下方法(與上述相同)下載此文件:
$attachment = SendMailAttachments::where('mail_id', $mailId)->where('filename', $attachmentName)->first();
if ($attachment) {
$filesPath = storage_path('app/sendmail_attachments');
return response()->download($filesPath . '/' . $attachment->physical_name);
}
它可以正常工作-文件已正確下載,我可以打開它。
為什么我無法打開用第一種方法下載的文件?
我使用Laravel 5.1和Ubuntu 16.04(如果有的話)。
編輯
當我對下載的文件運行file
命令時,結果是data
。 當我在存儲中的文件上運行它時,結果是正確的JPEG image data
。
嘗試使用響應視圖文檔添加標題
$headers = array('Content-Type' => ' image/jpeg');
$filesPath = storage_path('app/knowledge_database_attachments');
return response()->download($filesPath,$attachment->physical_name,$headers);
注意:管理文件下載的Symfony HttpFoundation要求下載的文件具有ASCII文件名。
問題是我在圖像流之前輸出了一些東西。
臨時解決方案:
$response = response()->download($filesPath . '/' . $attachment->physical_name);
ob_end_clean();
return $response;
永久解決方案:查找輸出內容並將其刪除。
在這里找到這個: https : //laracasts.com/discuss/channels/laravel/image-is-being-thrown-as-a-white-blank-image?page=1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.