2016-05-25 29 views
2

Laravelファイルシステムを使用してAmazon S3にファイルをアップロードしています。アップロードプロセスは素晴らしいですが、ファイルをダウンロードすると破損します。私は手動でS3バケットからファイルをダウンロードしたので、ファイルが破損することはないので、問題はアップロードではないと考えました。ファイルシステムを使用してAWS S3からダウンロードしたLaravelファイルが破損する

/** 
* 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) 
{ 
    $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 . '"' 
    ]); 
} 

/** 
* @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 . '"' 
    ]); 
} 

そして、これをファイルは破損します。どんな助けもありがとう!

+0

'$ file_info->バッファ($ファイル)'の値がどのようなものです:ここでは

はpresigned URLを使用せずにコードのですか? – maiorano84

+0

@ maiorano84私は主にPDF、Doc/x、Dwgで作業するつもりです。ストリーミングされたファイルに応じて、 '' application/pdf "'、 '' application/vnd.openxmlformats-officedocument.wordprocessingml.document "'または '' image/vnd.dwg "'を '$ file_info-> buffer( $ファイル) ' – enriqg9

+0

gigglesのためだけにヘッダーを次のように設定してください:' [ 'Content-Type' => 'application/octet-stream'、 'Content-Disposition' => '添付ファイル。ファイル名= "'。$ document-> name"' ' ' – maiorano84

答えて

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 . '"' 
    ]); 
} 
関連する問題