Mash Square's avatar

Multipart Uploading to S3, Fopen issues

Hi all!

How can I set correctly fopen? Since I don't know the initial file position I get a 500 error when trying to upload.

  • I would need to use multi-part upload to optimize transfer speed.
  • My website will be servless and will be running on Vapor, thus I can not save the file to local before uploading to S3.
  • I want to upload stream the files to the S3 Bucket, files are chosen using a form and I don't know their initial local path on client's computer...There are some alternatives show on the AWS docs but they all assume you will know already the initial location of the files...
$s3Client = new S3Client([
    'profile' => 'default',
    'region' => 'us-east-2',
    'version' => '2006-03-01'
]);

$bucket = 'your-bucket';
$key = 'my-file.zip';

// Using stream instead of file path
$source = fopen('/path/to/large/file.zip', 'rb');

$uploader = new ObjectUploader(
    $s3Client,
    $bucket,
    $key,
    $source
);

do {
    try {
        $result = $uploader->upload();
        if ($result["@metadata"]["statusCode"] == '200') {
            print('<p>File successfully uploaded to ' . $result["ObjectURL"] . '.</p>');
        }
        print($result);
    } catch (MultipartUploadException $e) {
        rewind($source);
        $uploader = new MultipartUploader($s3Client, $source, [
            'state' => $e->getState(),
        ]);
    }
} while (!isset($result));

fclose($source);
0 likes
2 replies
Mash Square's avatar

Thanks for the answer! I overlooked it! BTW in your experience does this work with large files as well? I can upload to S3 but the speed is REALLY slow and the SDKs seem to be a nightmare because I need to know the location of the source file beforehand...

Please or to participate in this conversation.