How to force the download of an object from an AWS bucket S3 with PHP?

8

I know how to upload an object to the AWS S3 Bucket this way:

try {
    $oClientAws->putObject(array(
        'Bucket' => 'bucket_test',
        'Key'    => 'fileName.jpg',
        'Body'   => fopen('path/to/file/fileName.jpg', 'r'),
        'ACL'    => 'public-read',
    ));            
} 
catch (Aws\Exception\S3Exception $e) {}

But I do not know how to force the download of an object I can use $oClientAws->GetObject (parametros ...) and change the header content type, but this only shows my file in the browser, but does not actually download the file.

Is there any right way to do this?

    
asked by anonymous 25.06.2015 / 22:52

2 answers

1

The author got the answer on SOen , I imported it so I might help other users.

Use the standalone S3 class (which I found is not very different from the AWS SDK) with getObject :

/**
* Get an object
*
* @param string $bucket Bucket name
* @param string $uri Object URI
* @param mixed $saveTo Filename or resource to write to
* @return mixed
*/
public static function getObject($bucket, $uri, $saveTo = false)
{
    $rest = new S3Request('GET', $bucket, $uri, self::$endpoint);
    if ($saveTo !== false)
    {
        if (is_resource($saveTo))
            $rest->fp =& $saveTo;
        else
            if (($rest->fp = @fopen($saveTo, 'wb')) !== false)
                $rest->file = realpath($saveTo);
            else
                $rest->response->error = array('code' => 0, 'message' => 'Unable to open save file for writing: '.$saveTo);
    }
    if ($rest->response->error === false) $rest->getResponse();

    if ($rest->response->error === false && $rest->response->code !== 200)
        $rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
    if ($rest->response->error !== false)
    {
        self::__triggerError(sprintf("S3::getObject({$bucket}, {$uri}): [%s] %s",
        $rest->response->error['code'], $rest->response->error['message']), __FILE__, __LINE__);
        return false;
    }
    return $rest->response;
}

Source: link

    
28.06.2015 / 20:47
1

Unfortunately there is no parameter to force the download. What you can do is:

  • Create a url of yours, for example, download.php, capture the Amazon object and use a source code similar to the below

    $result = $s3->getObject(array(
    'Bucket' => $bucket,
    'Key'    => $keyname
    ));
    header("Content-Type: {$result['ContentType']}");
    echo $result['Body'];
    
16.06.2017 / 01:35