How to upload a screenshot using html2canvas?
Solution 1:
I have modified and annotated the method from this answer. It sends only one file, with a given name, composed from a <canvas>
element.
if (!('sendAsBinary' in XMLHttpRequest.prototype)) {
XMLHttpRequest.prototype.sendAsBinary = function(string) {
var bytes = Array.prototype.map.call(string, function(c) {
return c.charCodeAt(0) & 0xff;
});
this.send(new Uint8Array(bytes).buffer);
};
}
/*
* @description Uploads a file via multipart/form-data, via a Canvas elt
* @param url String: Url to post the data
* @param name String: name of form element
* @param fn String: Name of file
* @param canvas HTMLCanvasElement: The canvas element.
* @param type String: Content-Type, eg image/png
***/
function postCanvasToURL(url, name, fn, canvas, type) {
var data = canvas.toDataURL(type);
data = data.replace('data:' + type + ';base64,', '');
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
var boundary = 'ohaiimaboundary';
xhr.setRequestHeader(
'Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.sendAsBinary([
'--' + boundary,
'Content-Disposition: form-data; name="' + name + '"; filename="' + fn + '"',
'Content-Type: ' + type,
'',
atob(data),
'--' + boundary + '--'
].join('\r\n'));
}
Solution 2:
This code works for me. It will generate screenshot by html2canvas, upload the screenshot to imgur api, and return the imgur url.
<button class="upload" >Upload to Imgur</button>
<script>
$(".upload").on("click", function(event) {
html2canvas($('body'), {
onrendered: function(canvas) {
document.body.appendChild(canvas);
try {
var img = canvas.toDataURL('image/jpeg', 0.9).split(',')[1];
} catch(e) {
var img = canvas.toDataURL().split(',')[1];
}
// open the popup in the click handler so it will not be blocked
var w = window.open();
w.document.write('Uploading...');
// upload to imgur using jquery/CORS
// https://developer.mozilla.org/En/HTTP_access_control
$.ajax({
url: 'http://api.imgur.com/2/upload.json',
type: 'POST',
data: {
type: 'base64',
// get your key here, quick and fast http://imgur.com/register/api_anon
key: 'your api key',
name: 'neon.jpg',
title: 'test title',
caption: 'test caption',
image: img
},
dataType: 'json'
}).success(function(data) {
w.location.href = data['upload']['links']['imgur_page'];
}).error(function() {
alert('Could not reach api.imgur.com. Sorry :(');
w.close();
});
},
});
});
</script>