用HTML5 File API 实现截图粘贴上传、拖拽上传

<!DOCTYPE html>
<html>
<head>
<title>test chrome paste image</title>
<style>
DIV#editable {
width: 400px;
height: 300px;
border: 1px dashed blue;
}
</style>
<script type="text/javascript">
window.onload = function () {
function paste_img(e) {
if (e.clipboardData.items) {
ele = e.clipboardData.items
for (var i = 0; i < ele.length; ++i) {
if (ele[i].kind == 'file' && ele[i].type.indexOf('image/') !== -1) {
var blob = ele[i].getAsFile();
window.URL = window.URL || window.webkitURL;
var blobUrl = window.URL.createObjectURL(blob);
console.log(blobUrl);
var new_img = document.createElement('img');
new_img.setAttribute('src', blobUrl);
document.getElementById('editable').appendChild(new_img);
convertImgToBase64(blobUrl, function (base64Img) {
// console.log(base64Img);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/ajax', true);
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE && /^2\d{2}$/.test(xhr.status)) {
}
}
xhr.send(base64Img);//把body字符串作为请求体发送到服务器端
});
}
}
} else {
alert('non-chrome');
}
}
document.getElementById('editable').onpaste = function () {
paste_img(event);
return false;
};
}
function convertImgToBase64(url, callback, outputFormat) {
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'),
img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function () {
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL(outputFormat || 'image/png');
callback.call(this, dataURL);
canvas = null;
};
img.src = url;
}
</script>
</head>
<body>
<div >
</div>
</body>
</html>