Created
July 10, 2016 10:24
-
-
Save alu96/7999303b3fe4d5459ec6fcaceda94bc3 to your computer and use it in GitHub Desktop.
Canvas FormData POST
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
<!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