Skip to content

Instantly share code, notes, and snippets.

@alu96
Created July 10, 2016 10:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alu96/c0611e4832972cdd0571f304400efe68 to your computer and use it in GitHub Desktop.
Save alu96/c0611e4832972cdd0571f304400efe68 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>
<script>
function dataURItoBlob (dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type: mimeString});
}
function createCanvas () {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 150, 75);
return c;
}
var canvas = createCanvas();
var dataURL = canvas.toDataURL('image/jpeg', 0.5);
var blob = dataURItoBlob(dataURL);
var fd = new FormData(document.forms[0]);
fd.append("image", blob);
// Upload image
var XHR = new XMLHttpRequest();
// We define what will happen if the data are successfully sent
XHR.addEventListener('load', function (event) {
console.log('Yeah! Data sent and response loaded.');
});
// We define what will happen in case of error
XHR.addEventListener('error', function (event) {
console.log('Oups! Something goes wrong.');
});
// We setup our request
XHR.open('POST', 'http://localhost:8080/test/upload');
// We just send our FormData object, HTTP headers are set automatically
XHR.send(fd);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment