如何将大型文件从S3流传输到laravel视图 [英] How to stream an large file from S3 to a laravel view

查看:69
本文介绍了如何将大型文件从S3流传输到laravel视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作大部分都在进行中,但是很难完成.

I have this mostly working but having a tough time finalizing it.

现在我有一条简单的路线:

For now I have a simple route:

Route::get('file/{id}/', 'FileController@fileStream')->name('file');

此路由连接到FileController中的一个动作:

this route connects to an action in the FileController:

public function fileStream($id){

    $audio = \App\Audio::where('id', $id)->first();

    $client = S3Client::factory([
        'credentials' => [
            'key'    => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
        ],
        'region' => env('S3REGION'),
        'version' => 'latest',
    ]);


    // Register the stream wrapper from an S3Client object
    $client->registerStreamWrapper();

    if ($stream = fopen('s3://[bucket_name]/'. $audio->audio_url, 'r')) {
        while (!feof($stream)) {
            echo fread($stream, 1024);
        }
        fclose($stream);
    }    
}

这适用于浏览器:如果我进入url:/file/1,它将查找正确的文件,然后在干净的浏览器窗口中得到:

This works to the browser: if I go to a url: /file/1 it looks up the right file, and in a clean browser window I get:

然后在我看来,我试图输出如下音频:

And then in my view I am trying to output the audio like:

   <audio>
      <source src="{{ url('file', ['id' => $section->id]) }}" type="{{ $section->audio_mime_type}}"></audio>
   </audio>

但是没有播放器输出到屏幕.

But no player is getting output to the screen.

TIA

推荐答案

您应使用Laravel 流式响应

You should use Laravel Streamed response

return response()->streamDownload(function () use ($audio) {
    if ($stream = fopen('s3://[bucket_name]/'. $audio->audio_url, 'r')) {
        while (!feof($stream)) {
            echo fread($stream, 1024);
            flush();
        }
        fclose($stream);
    }    
}, 'file-name.ext');

这篇关于如何将大型文件从S3流传输到laravel视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆