Skip to content

Instantly share code, notes, and snippets.

@ericktai
Created April 24, 2012 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ericktai/2483141 to your computer and use it in GitHub Desktop.
Save ericktai/2483141 to your computer and use it in GitHub Desktop.
Send Binary File with StackMob
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="http://static.stackmob.com/js/json2-min.js"></script>
<script type="text/javascript" src="http://static.stackmob.com/js/underscore-1.3.0-min.js"></script>
<script type="text/javascript" src="http://static.stackmob.com/js/backbone-0.5.3-min.js"></script>
<script type="text/javascript" src="http://static.stackmob.com/js/stackmob-js-0.1.1-min.js"></script>
<script type="text/javascript">
/* <![CDATA[ */
StackMob.init({
appName: 'stackmob_app_name',
clientSubdomain: 'stackmob_subdomain',
apiVersion: 0
});
function getStackMobBinaryString(filename, filetype, base64EncodedData) {
var binaryValueString = 'Content-Type: ' + filetype +
'\nContent-Disposition: attachment; filename=' + filename +
'\nContent-Transfer-Encoding: base64\n\n' + base64EncodedData;
return binaryValueString
}
/* ]]> */
</script>
</head>
<body>
<table>
<tr>
<td>File to Encode:</td>
<td><input type="file" id="files" name="files[]" multiple /></td>
</tr>
</table>
<script type="text/javascript">
//Define your Todo class once on the page.
var Todo = StackMob.Model.extend({
schemaName: 'todo'
});
var todoInstance = new Todo();
var binaryFileName = "profile_pic";
var fileContent;
var fileName;
var contentType;
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
// Closure to capture the file information
reader.onload = (function(theFile) {
return function(e) {
/*
e.target.result will return "data:image/jpeg;base64,[base64 encoded data]...".
We only want the "[base64 encoded data] portion, so strip out the first part
*/
var base64Content = e.target.result.substring(e.target.result.indexOf(',') + 1, e.target.result.length);
var fileName = theFile.name;
var fileType = theFile.type;
todoInstance.set(binaryFileName, getStackMobBinaryString(fileName, fileType, base64Content));
todoInstance.save();
};
})(f);
// Read in the file as a data URL
fileContent = reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment