Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BlobBuilder ruins binary data

I have a problem with BlobBuilder (Chrome11) I try to obtain an image from server with XHR request. Then i try to save it to local FS with BlobBuilder / FileWriter. Every example on the internet is about working with text/plain mime type and these examples work fine. But when i try to write binary data obtained with XHR, file size becomes about 1.5-2 times bigger than the original file size. And it cannot be viewed in Picasa / Eye Of Gnome.

var xhr = new XMLHttpRequest();
var photoOrigUrl = 'http://www.google.ru/images/nav_logo72.png';
xhr.open('GET', photoOrigUrl, true);
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        var contentType = xhr.getResponseHeader('Content-type');

        fsLink.root.getFile('nav_logo72.png', {'create': true}, function(fileEntry) {
            fileEntry.createWriter(function(fileWriter) {
                var BlobBuilderObj = new (window.BlobBuilder || window.WebKitBlobBuilder)();
                BlobBuilderObj.append(xhr.responseText);

                fileWriter.write(BlobBuilderObj.getBlob(contentType));
            }, function(resultError) {
                console.log('writing file to file system failed (   code ' + resultError.code + ')');
            });
        });
    }
}

xhr.send();

fsLink exists, this is extension.

like image 307
Dmitrii Sorin Avatar asked May 29 '11 21:05

Dmitrii Sorin


2 Answers

The problem is that BlobBuilder.append(xhr.responseText) is detecting its argument as a UTF-8 string, which is what XHR returns, and not binary data, which is what it really is. There's a couple of tricks to get the BlobBuilder reading it as binary data instead of string data:

var xhr = new XMLHttpRequest();
var photoOrigUrl = 'http://www.google.ru/images/nav_logo72.png';
xhr.open('GET', photoOrigUrl, true);

// CHANGE 1: This stops the browser from parsing the data as UTF-8:
xhr.overrideMimeType('text/plain; charset=x-user-defined');

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        var contentType = xhr.getResponseHeader('Content-type');

        fsLink.root.getFile('nav_logo72.png', {'create': true}, function(fileEntry) {
            fileEntry.createWriter(function(fileWriter) {

                // CHANGE 2: convert string object into a binary object
                var byteArray = new Uint8Array(xhr.response.length);
                for (var i = 0; i < xhr.response.length; i++) {
                    byteArray[i] = xhr.response.charCodeAt(i) & 0xff;
                }

                var BlobBuilderObj = new (window.BlobBuilder || window.WebKitBlobBuilder)();

                // CHANGE 3: Pass the BlobBuilder an ArrayBuffer instead of a string
                BlobBuilderObj.append(byteArray.buffer);

                // CHANGE 4: not sure if it's needed, but keep only the necessary
                // part of the Internet Media Type string
                fileWriter.write(BlobBuilderObj.getBlob(contentType.split(";")[0]));
            }, function(resultError) {
                console.log('writing file to file system failed (   code ' + resultError.code + ')');
            });
        });
    }
}

xhr.send();

This gave me a file with the same length as what xhr.getResponseHeader('Content-Length') suggests it should have been.

like image 121
Stoive Avatar answered Oct 15 '22 20:10

Stoive


You can use xhr.responseType='arraybuffer' though:

BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;

var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/image.png', true);
xhr.responseType = 'arraybuffer';

xhr.onload = function(e) {
  if (this.status == 200) {
    var bb = new BlobBuilder();
    bb.append(this.response); // Note: not xhr.responseText

    var blob = bb.getBlob('image/png');
    ...
  }
};

xhr.send();
like image 3
ebidel Avatar answered Oct 15 '22 20:10

ebidel