Uploading Images to S3 Specify Content Type Using Cold Fusion

Recently, I've been doing a lot of experimenting with ColdFusion and Amazon'due south Simple Storage Service (S3). Up until now, this has primarily involved using ColdFusion as a proxy to upload files and provide pre-signed (query-cord authenticated) URLs. As I've been doing this exploration, a few people have mentioned that Amazon S3 allows web-users to upload files directly to an S3 saucepan using a regular HTTP Class Mail. This sounds intriguing, and then I figured I would give information technology a try.

When uploading to Amazon S3 using a Course POST, you still need ColdFusion (or another server-side linguistic communication) in order to generate the authorization signature for the request. The signal of the Class POST is non to remove the need for a server-side infrastructure; rather, it is intended only to remove the demand to use your server a proxy for the upload.

If the upload to S3 is successful, Amazon volition redirect the request to the "success url" you lot ascertain in the form data. If the upload fails, all the same, at that place is no redirect. Instead, Amazon returns its typical XML-encoded error response.

When posting to Amazon S3 using a form POST, y'all tin can simply upload one file at a time. And, y'all need to provide a policy for the upload. This policy describes the asking data and all the constraints that Amazon needs to utilize to the diverse form fields. I don't have a super in-depth understanding of how this policy works - my demo was cobbled together using the example provided on the Amazon Web Services blog.

That said, the following script prepares an upload policy and and then presents the user with an HTTP Form for the upload. You may notice that both the policy and the form data seem to indicate that an epitome will be uploaded. It is important to understand that this defines the meta data that will be stored with the resource on Amazon S3 and in no way limits the type of file that can be uploaded. If a user selects a non-epitome file, information technology will be uploaded all the same; it volition simply exist stored with an illogical content-type value.

                  <cfscript>   	// Include our Amazon S3 credentials. 	include "../credentials.cfm";   	// Fix the Success url that Amazon S3 will redirect to if the 	// FORM Postal service has been submitted successfully. 	// NOTE: If the course post fails, Amazon volition present an error 	// message - there is non mistake-based redirect. 	successUrl = ( 		"http://" & cgi.server_name & 		getDirectoryFromPath( cgi.script_name ) & "success.cfm" 	);  	// The expiration must divers in UCT time. 	expiration = dateConvert( "local2utc", dateAdd( "h", 1, now() ) );  	// Annotation: When formatting the UTC time, the hours must be in 24- 	// 60 minutes time; therefore, make sure to use "HH", not "hh" and so that 	// your policy don't elapse prematurely. 	policy = { 		"expiration" = ( 			dateFormat( expiration, "yyyy-mm-dd" ) & "T" & 			timeFormat( expiration, "HH:mm:ss" ) & "Z" 		), 		"conditions" = [ 			{ 				"saucepan" = aws.bucket 			}, 			{ 				"acl" = "individual" 			}, 			{ 				"success_action_redirect" = successUrl 			}, 			[ "starts-with", "$primal", "/course-post/" ], 			[ "starts-with", "$Content-Type", "image/" ], 			[ "content-length-range", 0, 10485760 ] // 10mb 		] 	};   	// ------------------------------------------------------ // 	// ------------------------------------------------------ //   	// The policy will be posted forth with the Class post equally a 	// hidden course field. Serialize it as JavaScript Object notation. 	serializedPolicy = serializeJson( policy );  	// Remove upwards the line breaks. 	serializedPolicy = reReplace( serializedPolicy, "[\r\north]+", "", "all" );  	// Encode the policy equally Base64 and then that it doesn't mess up 	// the form post information at all. 	encodedPolicy = binaryEncode( 		charsetDecode( serializedPolicy, "utf-8" ) , 		"base64" 	);   	// ------------------------------------------------------ // 	// ------------------------------------------------------ //   	// To make certain that no 1 tampers with the Form Mail service, create 	// hashed message hallmark code of the policy content. 	// NOTE: The hmac() office was added in ColdFusion 10. 	hashedPolicy = hmac( 		encodedPolicy, 		aws.secretKey, 		"HmacSHA1", 		"utf-8" 	);  	// Encode the message hallmark code in Base64. 	encodedSignature = binaryEncode( 		binaryDecode( hashedPolicy, "hex" ), 		"base64" 	);   </cfscript>   <!--- ----------------------------------------------------- ---> <!--- ----------------------------------------------------- --->   <!--- Reset the output buffer and set up the page encoding. ---> <cfcontent type="text/html; charset=utf-viii" />  <cfoutput>  	<!doctype html> 	<html> 	<head> 		<meta charset="utf-eight" />  		<title> 			Uploading Files To Amazon S3 Using A Form Post And ColdFusion 		</title> 	</caput> 	<body>  		<h1> 			Uploading Files To Amazon S3 Using A Form Postal service And ColdFusion 		</h1>  		<form 			method="post" 			activeness="https://#aws.saucepan#.s3.amazonaws.com/" 			enctype="multipart/form-data">  			<input type="subconscious" proper noun="AWSAccessKeyId" value="#aws.accessID#" /> 			<input type="hidden" name="key" value="/course-post/${filename}" /> 			<input type="hidden" name="Content-Type" value="image/*" /> 			<input type="hidden" proper noun="acl" value="private" /> 			<input type="hidden" name="success_action_redirect" value="#htmlEditFormat( successUrl )#" />  			<!--- Base64-encoded policy and request signature. ---> 			<input blazon="subconscious" name="policy" value="#encodedPolicy#" /> 			<input type="subconscious" name="signature" value="#encodedSignature#" />  			<p> 				Select your file: 			</p>  			<!--- 				Notation: The file upload must be the LAST field in the 				form post and must exist called "file". 			---> 			<p> 				<input name="file" type="file" size="40" /> 			</p>  			<p> 				<input type="submit" value="Upload Image" /> 			</p>  		</class>  	</body> 	</html>  </cfoutput>                                  

In one case the file is candy, Amazon volition redirect the browser to the URL divers in the "success_action_redirect" form field. When doing this, Amazon will add iii query cord parameters for:

  • saucepan
  • central
  • etag

The "central" value is the resource cardinal at which the uploaded document was stored. This value may or may not start with a leading "/" depending on how your form fields were configured. The HTTP Form POST upload volition work with or without the leading "/" on your resource cardinal; however, if y'all don't provide in the form, you'll take to add it to the cardinal in the query string parameter.

To test that the upload was successful, my "success_action_redirect" page created a pre-signed (query cord authenticated) URL and rendered the uploaded image using an HTML IMG tag:

                  <cfscript>   	// When Amazon S3 redirects the Grade POST to the success URL, 	// it will pass the following parameters in the URL. 	// Annotation: The etag value is quoted (ie, "abc123"). 	param name="url.saucepan" blazon="cord"; 	param proper noun="url.cardinal" type="cord"; 	param name="url.etag" type="string";   	// ------------------------------------------------------ // 	// ------------------------------------------------------ //   	// Include our Amazon S3 credentials. 	include "../credentials.cfm";  	// At present that we have the resource and the saucepan to which it was 	// posted, nosotros can construct a full URL and generate a pre-signed, 	// authorized URL. 	resource = ( "/" & url.bucket & url.primal );  	// The expiration is defined as the number of seconds since 	// epoch - as such, nosotros need to effigy out what our local timezone 	// epoch is. 	localEpoch = dateConvert( "utc2local", "1970/01/01" );  	// The resource will expire in +i day. 	expiration = dateDiff( "s", localEpoch, ( now() + 1 ) );  	// Build up the content of the signature (excluding Content-MD5 	// and the mime-type). 	stringToSignParts = [ 		"GET", 		"", 		"", 		expiration, 		resource 	];  	stringToSign = arrayToList( stringToSignParts, chr( 10 ) );  	// Generate the signature as a Base64-encoded string. 	// NOTE: Hmac() function was added in ColdFusion 10. 	signature = binaryEncode( 		binaryDecode( 			hmac( stringToSign, aws.secretKey, "HmacSHA1", "utf-eight" ), 			"hex" 		), 		"base64" 	);  	// Prepare the signature for use in a URL (to make certain none of 	// the characters go transported improperly). 	urlEncodedSignature = urlEncodedFormat( signature );   </cfscript>  <!--- Reset the output buffer and fix the page encoding. ---> <cfcontent type="text/html; charset=utf-eight" />  <cfoutput>  	<!doctype html> 	<html> 	<head> 		<meta charset="utf-eight" />  		<title> 			Your Upload To Amazon S3 Was Successful! 		</title> 	</head> 	<body>  		<h1> 			Your Upload To Amazon S3 Was Successful! 		</h1>  		<p> 			<img src="https://s3.amazonaws.com#resources#?AWSAccessKeyId=#aws.accessID#&Expires=#expiration#&Signature=#urlEncodedSignature#" /> 		</p>  	</body> 	</html>  </cfoutput>                                  

This is a pretty cool feature, but I am non certain how frequently I would utilise information technology. One time you upload a file to your server, transferring it to Amazon S3 should be negligible (considering that most hosting providers take massive net backbones). I gauge it volition depend on how much (if whatever) mail-upload processing you will need to practise in your specific workflow. Definitely this is something that warrants farther exploration.

Black Lives Matter

Ad for InVision App, Inc prototying platform.


amiesefors1950.blogspot.com

Source: https://www.bennadel.com/blog/2500-uploading-files-to-amazon-s3-using-a-form-post-and-coldfusion.htm

0 Response to "Uploading Images to S3 Specify Content Type Using Cold Fusion"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel