Created
June 7, 2013 10:42
-
-
Save joaoffcosta/5728483 to your computer and use it in GitHub Desktop.
How to use S3 browser upload using POST form without leaving the page and with error and success handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>S3 POST Form</title> | |
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> | |
</head> | |
<script src="http://code.jquery.com/jquery-1.9.1.js"></script> | |
<script type="text/javascript"> | |
function canAccessIFrame(iframe) { | |
var html = null; | |
try { | |
// deal with older browsers | |
var doc = iframe.contentDocument || iframe.contentWindow.document; | |
html = doc.body.innerHTML; | |
} catch(err){ | |
// do nothing | |
} | |
return(html !== null); | |
} | |
function iFrameLoaded() { | |
// both error (https://bucket_name.s3.amazonaws.com/) and success (http://www.google.com) | |
// cases have a different domain which means that the iframe won't be accessible | |
if (!canAccessIFrame($('#S3ResponseIFrame')[0])) { | |
alert('upload finished'); | |
$('#loadedImg').error(function(){ | |
alert('upload failed'); | |
}) | |
$('#loadedImg').load(function(){ | |
alert('upload worked!!!!!!'); | |
}) | |
$('#loadedImg').attr('src','https://bucket_name.s3.amazonaws.com/image/' + _fileName); | |
} | |
} | |
var _fileName = ""; | |
function getFileName(file) { | |
_fileName = new Date().getTime() + '.' + file.split('.').pop(); | |
return _fileName; | |
} | |
function s3FormSubmit() { | |
$('#s3Form')[0].key.value = 'image/' + getFileName($('#s3Form')[0].file.value); | |
$('#s3Form').submit(); | |
} | |
</script> | |
<body> | |
<form id="s3Form" action="https://bucket_name.s3.amazonaws.com/" method="post" enctype="multipart/form-data" target="S3ResponseIFrame"> | |
<input type="hidden" name="key" value=""> | |
<input type="hidden" name="AWSAccessKeyId" value="YOUR_ACCESS_KEY"> | |
<input type="hidden" name="acl" value="public-read"> | |
<input type="hidden" name="success_action_redirect" value="http://www.google.com"> | |
<input type="hidden" name="policy" value="YOUR_POLICY"> | |
<input type="hidden" name="signature" value="YOUR_SIGNATURE="> | |
<input type="hidden" name="Content-Type" value="image/png"> | |
<!-- Include any additional input fields here --> | |
File to upload to S3: | |
<input name="file" type="file"> | |
<br> | |
<input type="button" onclick="s3FormSubmit()" value="Upload File to S3"> | |
</form> | |
<img id="loadedImg" src=""></img> | |
<iframe id="S3ResponseIFrame" onload="iFrameLoaded()"></iframe> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment