我使用Laravel文件系统将文件上传到Amazon S3。然而,当我下载文件时,上传过程很有效。我已经手动下载了S3存储桶中的文件,这样文件就不会被破坏,所以我认为问题不在于上传。
我上传的文件如下:
/**
* Upload the file to Amazon S3.
*
* @param UploadedFile $file
* @param $path
* @return $this|bool
*/
protected function upload(UploadedFile $file, $path)
{
$this->filename = $path . '/' . time() . '_' . str_replace(' ', '-', $file->getClientOriginalName());
$disk = Storage::cloud();
if ($disk->put($this->filename, fopen($file, 'r+'))) {
$this->save();
return $this;
}
return false;
}
要下载,我试过这个:
/**
* @param Document $document
* @return Response
*/
public function download(Document $document)
{
$file = Storage::cloud()->get($document->path);
$file_info = new finfo(FILEINFO_MIME_TYPE);
return response($file, 200)->withHeaders([
'Content-Type' => $file_info->buffer($file),
'Content-Disposition' => 'inline; filename="' . $document->name . '"'
]);
}
而且:
/**
* @param Document $document
* @return Response
*/
public function download(Document $document)
{
$stream = Storage::cloud()->getDriver()->readStream($document->path);
$file = stream_get_contents($stream);
$file_info = new finfo(FILEINFO_MIME_TYPE);
return response($file, 200)->withHeaders([
'Content-Type' => $file_info->buffer($file),
'Content-Disposition' => 'inline; filename="' . $document->name . '"'
]);
}
使用这两种下载功能,我都会获得文件,但是它们会被破坏。任何帮助表示赞赏!
答案 0 :(得分:3)
问题是输出缓冲区包含空格。在返回响应之前使用ob_end_clean()
解决了问题,但在打开<?php
标记之前在文件上找到空格时,无需使用ob_end_clean()
。
以下是不使用预先签名的网址的代码:
/**
* Download document from S3.
*
* @param Document $document
* @return Response
*/
public function download(Document $document)
{
$s3Client = Storage::cloud()->getAdapter()->getClient();
$stream = $s3Client->getObject([
'Bucket' => 'bucket',
'Key' => $document->path
]);
return response($stream['Body'], 200)->withHeaders([
'Content-Type' => $stream['ContentType'],
'Content-Length' => $stream['ContentLength'],
'Content-Disposition' => 'inline; filename="' . $document->name . '"'
]);
}