Skip to content

Instantly share code, notes, and snippets.

@dshster
Created February 11, 2015 21:01
Show Gist options
  • Save dshster/f0330eca52c0bd775371 to your computer and use it in GitHub Desktop.
Save dshster/f0330eca52c0bd775371 to your computer and use it in GitHub Desktop.
Drag and drop, resize and xhr post
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<title>Filereader</title>
</head>
<body>
<div id="dragarea" class="drag-area"></div>
<script src="scripts.js"></script>
</body>
</html>
if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
value: function (callback, type, quality) {
var binStr = atob(this.toDataURL(type, quality).split(',')[1]),
len = binStr.length,
arr = new Uint8Array(len);
for (var i=0; i<len; i++) {
arr[i] = binStr.charCodeAt(i);
}
callback(new Blob([arr], { type: type || 'image/png' }));
}
});
}
(function(window, document) {
'use strict';
var target = document.getElementById('dragarea');
var fileToDataUrl = function(file) {
var reader = new window.FileReader();
return new Promise(function(resolve, reject) {
reader.onload = function(event) {
resolve(event.target.result);
};
reader.readAsDataURL(file);
});
};
var getImageData = function(dataUrl, width, height) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var image = new Image();
return new Promise(function(resolve, reject) {
image.onload = function() {
var img = this;
width == null && (width = Math.round(img.width * height / img.height));
height == null && (height = Math.round(img.height * width / img.width));
canvas.width = width;
canvas.height = height;
context.drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height);
canvas.toBlob(function(blob) {
resolve(blob)
}, 'image/png');
};
image.src = dataUrl;
});
};
var filesUpload = function(files) {
var xhr = new XMLHttpRequest();
var file;
if (files.length) {
file = files[0];
if (file.type.match(/image.*/) && 0 < file.size) {
fileToDataUrl(file)
.then(function(dataUrl) {
getImageData(dataUrl, 200)
.then(function(blob) {
console.log(blob)
xhr.open('POST', '/upload');
xhr.setRequestHeader('Content-Type', blob.type);
xhr.send(blob);
});
});
}
}
};
target.addEventListener('dragenter', function(event) {
});
target.addEventListener('dragleave', function(event) {
});
target.addEventListener('dragover', function(event) {
event.dataTransfer.dropEffect = 'copy';
event.stopPropagation();
event.preventDefault();
});
target.addEventListener('drop', function(event) {
event.stopPropagation();
event.preventDefault();
filesUpload(event.dataTransfer.files)
});
})(window, window.document)
.drag-area {
width: 500px;
height: 400px;
background-color: darkgray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment