Laravel download file from S3 route (not open in browser)

痞子三分冷 提交于 2019-12-13 07:41:15

问题


I have the following route that will load a file from the given URL, I need this to actually download the file (mp4, jpg, pdf) rather than open in the browsers in built viewer.

// Download from CDN Route
Route::get('cdn/{url}', function($url)
    {   
        return Redirect::away($url);    
    })->where('url', '(.*)');

All files are stored externally so apparently Resource::download() wouldn't actually work.

All I have available to me is the Amazon URL: https://mybucket.s3.amazonaws.com/folder/filename.pdf

Any suggestions on how to force the browser to download the file from S3?


回答1:


In my case simple anchor link is downloading the file ...

<a href="https://mybucket.s3.amazonaws.com/folder/filename.pdf"> file name </a>



回答2:


Try this code.

Update composer with flysystem

 $path = 'https://mybucket.s3.amazonaws.com/folder/filename.pdf';
            if(Storage::disk('s3')->has($path)){
                $data = Storage::disk('s3')->get($path);
                $getMimeType = Storage::disk('s3')->getMimetype($path);
                $newFileName = 'filename.pdf'; 
                $headers = [
                            'Content-type' => $getMimeType, 
                            'Content-Disposition'=>sprintf('attachment; filename="%s"', $newFileName)
                            ];
                return Response::make($data, 200, $headers);
            }



回答3:


pari answer download empty file.

$s3Client = AWS::createClient('s3');

$stream = $s3Client->getObject(

     [
       'Bucket' => 'bucket name',
       'Key'    => 'filename',
       'SaveAs' => '/tmp'.filename
   ]);

return response($stream['Body'], 200)->withHeaders([

    'Content-Type'        => $stream['ContentType'],
    'Content-Length'      => $stream['ContentLength'],
    'Content-Disposition' => 'attachment; filename="' .{filename with extention} . '"'
]);



回答4:


How can we download a video with an external link from another server. It's not s3. It's a normal server, files are there, but it doesn't work. I have written this code

                $filename = $video->video_id;
                $tempFile = tempnam(sys_get_temp_dir(), $filename);
//              dd($tempFile);

                copy($video->path, $tempFile);
                header("Content-Disposition: attachment; filename = ".$filename);
                header("X-Accel-Redirect: ".$filename);

                return response()->download($tempFile, $filename);


来源:https://stackoverflow.com/questions/32095572/laravel-download-file-from-s3-route-not-open-in-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!