我正在使用Laravel的存储外观,我可以将pdf上传到S3,我也可以获取()其内容,但我无法将其显示或下载到最终用户作为实际的pdf文件。它看起来像原始数据。这是代码:
$file = Storage::disk($storageLocation)->get($urlToPDF);
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename='file.pdf'");
echo $file;
如何做到这一点?我检查了几篇文章(和SO),但没有一篇文章适合我。
答案 0 :(得分:6)
我认为这样的事情将在L5.2中完成:
public function download($path)
{
$fs = Storage::getDriver();
$stream = $fs->readStream($path);
return \Response::stream(function() use($stream) {
fpassthru($stream);
}, 200, [
"Content-Type" => $fs->getMimetype($path),
"Content-Length" => $fs->getSize($path),
"Content-disposition" => "attachment; filename=\"" .basename($path) . "\"",
]);
}
答案 1 :(得分:3)
您可以使用getObjectUrl方法
创建下载网址这样的事情:
$downloadUrl = $s3->getObjectUrl($bucketname, $file, '+5 minutes', array(
'ResponseContentDisposition' => 'attachment; filename=$file,'Content-Type' => 'application/octet-stream',
));
并将该url传递给用户。这会将用户引导到将启动文件下载的amzon页面(该链接将有效5分钟 - 但您可以更改它)
另一个选项是,首先将该文件保存到您的服务器,然后让用户从您的服务器下载该文件
答案 2 :(得分:3)
您可以使用此代码(用目录和文件名替换)....
Storage :: disk('s3')-> download('bucket-directory / filename');
答案 3 :(得分:0)
$filename = 'test.pdf';
$filePath = storage_path($filename);
$header = [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$filename.'"'
];
return Response::make(file_get_contents($filePath), 200, $header);
答案 4 :(得分:0)
如果您的存储桶是私有的,则可以通过这种方式获取下载文件的网址。
$disk = \Storage::disk('s3');
if ($disk->exists($file)) {
$command = $disk->getDriver()->getAdapter()->getClient()->getCommand('GetObject', [
'Bucket' => \Config::get('filesystems.disks.s3.bucket'),
'Key' => $file,
'ResponseContentDisposition' => 'attachment;'
]);
$request = $disk->getDriver()->getAdapter()->getClient()->createPresignedRequest($command, '+5 minutes');
$url = (string)$request->getUri();
return response()->json([
'status' => 'success',
'url' => $url
]);
}
答案 5 :(得分:0)
在Laravel 5.7中,可以使用streamDownload
:
return response()->streamDownload(function() use ($attachment) {
echo Storage::get($attachment->path);
}, $attachment->name);
答案 6 :(得分:0)
$d = file_full_path_here...
$d = str_replace(' ', '%20', $d); //remove the white space in url
ob_end_clean();
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=" . $d);
header("Content-Type: application/pdf");
return readfile($d);
答案 7 :(得分:-3)
我明白了。愚蠢的错误。我不得不从文件名中删除单引号。
修正:
$file = Storage::disk($storageLocation)->get($urlToPDF);
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=file.pdf");
echo $file;