Question

I am trying to take a file that is hosted on Amazon S3 and upload it to another server using a Content-Type: multipart/form-data post request. I can use Curl --form for this but I am not sure how to get the S3 file to behave like a local file so that I can do something like this.

curl -F "file=@localfile;filename=nameinpost" url.com

I have guzzle set up so that I can use the stream wrapper like this

$this->guzzleClient->registerStreamWrapper(); $data = file_get_contents('s3://buck/test-file.jpg');

If I can get this stream to work that would be great, or is it only possible to use a local file? What is the most optimized way to do this sort of thing?

Was it helpful?

Solution 2

I came up with something like this.

//...configure an s3client
$this->s3client->registerStreamWrapper();

$filename = sys_get_temp_dir() .'/'. $unique_name;
$handle = fopen($filename, 'w+');
$bytes_written = fwrite( $handle, file_get_contents('s3://bucket/test-file.jpg'));

//...configure a Guzzle client

//Guzzle 3.0
$request = $this->client->post('image')->addPostFile('images', $filename);
$response = $request->send();

//Guzzle 4.0
$request = $this->client->createRequest('POST', 'images');
$request->getBody()->addFile(new PostFile('image', $handle));
$response = $this->client->send($request);

//remove the file
unlink($filename);

Guzzle 4.0 also has some newer features allowing streams to be used directly without having to create this temporary file. However I was not able to get this working with a service that was expecting a form based file upload following http://www.faqs.org/rfcs/rfc1867.html. If it is possible to use the stream that would be even better!

For more details see "Better POST File support" here http://mtdowling.com/blog/2014/03/15/guzzle-4-rc, The transition from version 3 to 4 did cause me some confusion. Make sure you know what version your clients are, and that you are reading docs for that version :)

OTHER TIPS

The AWS SDK for PHP, which uses Guzzle, provides a stream wrapper specifically for S3. See Amazon S3 Stream Wrapper.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top