Skip to content

Instantly share code, notes, and snippets.

@bromanko
Last active December 12, 2016 02:07
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bromanko/4692428 to your computer and use it in GitHub Desktop.
Save bromanko/4692428 to your computer and use it in GitHub Desktop.
File uploading directly to S3 from an iOS app.
require 'base64'
require 'openssl'
require 'digest/sha1'
policy_document = '{
"expiration": "2020-01-01T00:00:00Z",
"conditions": [
{"bucket": "YOUR_BUCKET"},
["starts-with", "$key", "uploads/"],
{"acl": "public-read"},
{"success_action_redirect": "http://localhost/"},
["starts-with", "$Content-Type", ""],
["content-length-range", 0, 31457280]
]
}'
aws_secret_key = 'YOUR_AWS_SECRET_KEY'
policy = Base64.encode64(policy_document).gsub("\n","")
signature = Base64.encode64(
OpenSSL::HMAC.digest(
OpenSSL::Digest::Digest.new('sha1'),
aws_secret_key, policy)
).gsub("\n","")
puts "Policy"
puts "======"
puts policy
puts "\n"
puts "Signature"
puts "========="
puts signature
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"https://YOUR_BUCKET.s3.amazonaws.com/"]];
NSDictionary *parameters = @{
@"key": @"uploads/${filename}",
@"AWSAccessKeyId": @"YOUR_AWS_ACCESS_KEY",
@"acl": @"public-read", // or private
@"success_action_redirect": @"http://localhost/",
@"policy": @"YOUR_POLICY_DOCUMENT_BASE64_ENCODED",
@"signature": @"YOUR_CALCULATED_SIGNATURE",
@"Content-Type": @"image/jpeg"
};
NSURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"test.jpg"], 1);
// The name of the field should be @"file"
[formData appendPartWithFileData:imageData name:@"file" fileName:@"upload.jpg" mimeType:@"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *op, id body) {
NSLog(@"Success");
} failure:^(AFHTTPRequestOperation *op, NSError *error) {
NSLog(@"Failure %@", error);
}];
[client enqueueHTTPRequestOperation:operation];
@bromanko
Copy link
Author

bromanko commented Feb 1, 2013

Based on the HTML form documentation provided by Amazon.

You'll need to create the policy document and signature based on the parameter dictionary being sent with the request. Update the variables in the Ruby script and execute it to get those values.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment