all articles

blob & filereader & image

2016-03-03 @sunderls

blob filereader js

data urls & blob urls

when previewing on browser end, you can use FileReader to read it as data urls or use blob to create blob urls.

but data urls can be very long, and <img > src attribute has about 2mb length max, so it is not good for larger files. I suggest using blob url

$file.on('change', function(){
    var blobURL = URL.createObjectURL($file.files[0]);

you can use blobURL as ordinary images.

browser cropping and server api

for cropping , you can use cropper.js.

for sending to server, you can use cropper.getCroppedCanvas() -> get data urls -> translate to blob -> api

var canvas = cropper.getCropperCanavs();
var dataUrl = canvas.toDataURL();
var blob = getBlobFromDatURL(dataUrl);
// call api

function getBlobFromDatURL(dataURL) {
    var BASE64_MARKER = ';base64,';
    if (dataURL.indexOf(BASE64_MARKER) == -1) {
        var parts = dataURL.split(',');
        var contentType = parts[0].split(':')[1];
        var raw = decodeURIComponent(parts[1]);

        return new Blob([raw], {type: contentType});

    var parts = dataURL.split(BASE64_MARKER);
    var contentType = parts[0].split(':')[1];
    var raw = window.atob(parts[1]);
    var rawLength = raw.length;

    var uInt8Array = new Uint8Array(rawLength);

    for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);

    return new Blob([uInt8Array], {type: contentType});