HTML Direct Upload Data to Amazon S3 Part 4: JavaScript Details

Overview

JavaScript combines all the things (authenticate data, file data, etc) to make a XMLHttpRequest to send data and thus directly upload the data into Amazon S3.

JavaScript Code

function btnUploadS3_onclick() {
	var fileInput = document.getElementById('fileS3');
	if ('' == document.getElementById('fileS3').value) {
		alert("Error: Empty File!");
		return ;
	}
	var fullPath = fileInput.value;
	var filename = fullPath.replace(/^.*[\\\/]/, '');
	var file = fileInput.files[0];

	var fd = new FormData();
	filekeypath = 'Prefix/' + filename;
	fd.append('key', filekeypath);
	fd.append('AWSAccessKeyId', document.getElementsByName("accesskey").item(0).value);
	fd.append('acl', 'public-read');
	fd.append('policy', document.getElementsByName("policy").item(0).value);
	fd.append('signature', document.getElementsByName("signature").item(0).value);
	fd.append("file", file, filekeypath);

	theURL = "http://s3.amazonaws.com/YourOwnBucketName/";
	var xhr = new XMLHttpRequest();
	xhr.open('POST', theURL);
	xhr.send(fd);
}

There are several things you need to pay attention to, otherwise, you won’t successfully upload the data, the Amazon S3 official document might not clearly state all these issues either:

1) The order of all the key/value pairs in the FormData structure matters! That is, if you got the wrong order say you append the signature before you apped acl or policy, it would fail!
2) Whatever you specify in the base64 policy during the server side PHP running time, when you make the request in JavaScript, all those specified should appear in the FormData too, like the key, liek the acl should be the same, and the key MUST start with “Prefix/” because this kind of information is already integrated into the policy and signature data. Amazon S3 would verify and check whether they are consistent and it determines you upload will be successful or not.
3) All the fields in the FormData should explain themselves well and all of them should be covered in previous posts. You might want to check Amazon S3 official documentation to know more fields so you can be more flexible to configure or restrict the user behavior on directly uploading data to your S3 storage.

Summary

In this post, we discussed how JavaScript combines all the things (authenticate data, file data, etc) to make a XMLHttpRequest to send data and thus directly upload the data into Amazon S3.

 


(Please specify the source  烟客旅人 sigmainfy — http://www.sigmainfy.com  as well as the original permalink

URL for any reprints,  and please do not use it for commercial purpose)

Written on October 7, 2014