How to upload a file with php and amazon S3 sdk?

I am trying to make my script show test.jpg in an Amazon S3 bucket via php. Here is what I still have:

require_once('library/AWS/sdk.class.php'); $s3 = new AmazonS3($key, $secret); $objInfo = $s3->get_object_headers('my_bucket', 'test.jpg'); $obj = $s3->get_object('my_bucket', 'test.jpg', array('headers' => array('content-disposition' => $objInfo->header['_info']['content_type']))); echo $obj->body; 

It just uploads the file data on the page. I think I also need to send a content header, which I thought was executed in the get_object () method, but it is not.

Note. I am using the SDK available here: http://aws.amazon.com/sdkforphp/

+6
source share
4 answers

I tried to work, the echo header of the content header before the echo response of the body of the object $.

 $objInfo = $s3->get_object_headers('my_bucket', 'test.jpg'); $obj = $s3->get_object('my_bucket', 'test.jpg'); header('Content-type: ' . $objInfo->header['_info']['content_type']); echo $obj->body; 
+12
source

Both of these methods work for me. The first way seems more concise.

  $command = $s3->getCommand('GetObject', array( 'Bucket' => 'bucket_name', 'Key' => 'object_name_in_s3' 'ResponseContentDisposition' => 'attachment; filename="'.$my_file_name.'"' )); $signedUrl = $command->createPresignedUrl('+15 minutes'); echo $signedUrl; header('Location: '.$signedUrl); die(); 

Or a more verbose, but still functional way.

  $object = $s3->getObject(array( 'Bucket' => 'bucket_name', 'Key' => 'object_name_in_s3' )); header('Content-Description: File Transfer'); //this assumes content type is set when uploading the file. header('Content-Type: ' . $object->ContentType); header('Content-Disposition: attachment; filename=' . $my_file_name); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); //send file to browser for download. echo $object->body; 
+8
source

I added the Content-Disposition header to getAuthenticatedUrl ();

  // Example $timeOut = 3600; // in seconds $videoName = "whateveryoulike"; $headers = array("response-content-disposition"=>"attachment"); $downloadURL = $s3->getAuthenticatedUrl( FBM_S3_BUCKET, $videoName, FBM_S3_LIFETIME + $timeOut, true, true, $headers ); 
+1
source

For PHP sdk3, change the last line of Maximus answer

  $object = $s3->getObject(array( 'Bucket' => 'bucket_name', 'Key' => 'object_name_in_s3' )); header('Content-Description: File Transfer'); //this assumes content type is set when uploading the file. header('Content-Type: ' . $object->ContentType); header('Content-Disposition: attachment; filename=' . $my_file_name); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); //send file to browser for download. echo $object["Body"]; 
+1
source

Source: https://habr.com/ru/post/897150/


All Articles