【问题标题】:Uploading multiple files to AWS S3 with Progress Bar使用进度条将多个文件上传到 AWS S3
【发布时间】:2016-10-17 10:49:01
【问题描述】:

我正在使用 Laravel 将多个文件上传到 S3 存储桶,但无法在客户端正确获取进度数据。

在客户端我有以下(简化):

var xhr = new XMLHttpRequest();
xhr.addEventListener("progress", updateProgress, false);
xhr.addEventListener("load", transferComplete, false);
xhr.open("POST", "my_url_to_upload");
xhr.send(formData);//formData is defined earlier and contains multiple files

function updateProgress(e) {
   console.log('updateProgress', e);
}

function transferComplete(e) {
   console.log("Files uploaded successfully.", e);
}

在 Laravel 方面:

$files  = \Input::file('file');
$s3     = \Storage::disk('s3');
foreach ($files as $file)
   {
     $file_name = "/some_folder/" . $file->getClientOriginalName();
     $s3->put($file_name, file_get_contents($file), 'public');
   } 

这非常适合将文件上传到 S3 存储桶。

问题是当上传多个文件时,客户端updateProgress函数只被调用一次,并且只有在所有文件都上传后(而不是在每个文件之后和上传期间)。

理想情况下,进度条会在文件上传期间定期更新,这样在上传大文件时,它会显示接近实时的进度(而不仅仅是在每个文件完成时)。

我如何让 Laravel(或一般的 PHP)在上传期间报告进度?

【问题讨论】:

    标签: php laravel file-upload amazon-s3 progress-bar


    【解决方案1】:

    以下是 SDK v3 中的操作方法:

    $client = new S3Client(/* config */);
    
    $result = $client->putObject([
        'Bucket'     => 'bucket-name',
        'Key'        => 'bucket-name/file.ext',
        'SourceFile' => 'local-file.ext',
        'ContentType' => 'application/pdf',
        '@http' => [
            'progress' => function ($downloadTotalSize, $downloadSizeSoFar, $uploadTotalSize, $uploadSizeSoFar) {
                printf(
                    "%s of %s downloaded, %s of %s uploaded.\n",
                    $downloadSizeSoFar,
                    $downloadTotalSize,
                    $uploadSizeSoFar,
                    $uploadTotalSize
                );
            }
        ]
    ]);
    

    这在 AWS 文档 - S3 Config section 中有说明。它通过暴露 GuzzleHttp 的 progress 属性调用来工作,如 this SO answer 中所述。

    我知道您的做法有些不同(使用 Streams),但我相信您可以根据自己的需要调整我的示例。

    【讨论】:

      猜你喜欢
      • 2017-09-25
      • 1970-01-01
      • 2018-12-13
      • 2016-08-07
      • 1970-01-01
      • 2022-01-23
      • 2012-08-18
      • 2020-04-29
      • 1970-01-01
      相关资源
      最近更新 更多