简体   繁体   中英

How to upload files directly to S3 using PHP and with progress bar

There are some similar questions but none have a good answers in how to upload files directly to S3 using PHP with progress bar. Is it even possible adding a progress bar without using Flash?

NOTE: I am referring to uploading from client browser directly to S3.

I've done this in our project. You can't upload directly to S3 using AJAX because of standard cross domain security policies; instead, you need to use either a regular form POST or Flash. You'll need to send the security policy and signature in a relatively complex process, as explained in the S3 docs .

YES , it is possible to do this in PHP 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) {
            // handle your progress bar percentage
            printf(
                "%s of %s downloaded, %s of %s uploaded.\n",
                $downloadSizeSoFar,
                $downloadTotalSize,
                $uploadSizeSoFar,
                $uploadTotalSize
            );
        }
    ]
]);

This is explained in the AWS docs - S3 Config section . It works by exposing GuzzleHttp's progress property-callable, as explained in this SO answer .

Technically speaking, with PHP you cannot go from client --> S3. Your solution, if you want to use PHP would either have to be designed as follows:

  • Client -> Web Server (PHP) -> Amazon S3
  • Client with PHP server embedded -> Amazon S3

The AWS PHP SDK: http://aws.amazon.com/sdkforphp/ is very well written and contains a specific example on how to send a file from a Client --> Server --> S3

With respects to the progress bar, there are many options available. A quick search of stackoverflow.com shows a question answered identical to this one:

It is possible to directly upload, but progress bar is impossible: http://undesigned.org.za/2007/10/22/amazon-s3-php-class/

see example_form in the downloads, direct upload from browser to S3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM