Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

javascript - Blob constructor browser compatibility

I am developping an application where I recieve image data stored in a uint8Array. I then transform this data to a Blob and then build the image url.

Simplified code to get data from server:

var array;

var req = new XMLHttpRequest();
var url = "img/" + uuid + "_" +segmentNumber+".jpg";
req.open("GET", url, true);
req.responseType = "arraybuffer";
req.onload = function(oEvent) {
    var data = req.response;    
    array = new Int8Array(data);      
};

Constructor:

out = new Blob([data], {type : datatype} );

The Blob contsructor is causing problem. It works fine on all browsers except Chrome on mobile and desktop devices.

Use of Blob:

// Receive Uint8Array using AJAX here
// array = ...
// Create BLOB
var jpeg = new Blob( [array.buffer], {type : "image/jpeg"});
var url = DOMURL.createObjectURL(jpeg);
img.src = url;

Desktop Chrome gives me a warnning : ArrayBuffer values are deprecated in Blob Constructor. Use ArrayBufferView instead.

Mobile Chrome gives me an error: illegal constructor

If I change the constructor to work on Chrome it fails on other browsers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So, these are actually two different problems. The Desktop Chrome warning was a bug in chrome which is fixed since 2013-03-21.

Mobile Chrome is giving you a TypeError because the blob constructor is not supported. Instead you must use the old BlobBuilder API. The BlobBuilder API has browser specific BlobBuilder constructors. This is the case for FF6 - 12, Chrome 8-19, Mobile Chrome, IE10 and Android 3.0-4.2.

var array = new Int8Array([17, -45.3]);

try{
  var jpeg = new Blob( [array], {type : "image/jpeg"});
}
catch(e){
    // TypeError old chrome and FF
    window.BlobBuilder = window.BlobBuilder || 
                         window.WebKitBlobBuilder || 
                         window.MozBlobBuilder || 
                         window.MSBlobBuilder;
    if(e.name == 'TypeError' && window.BlobBuilder){
        var bb = new BlobBuilder();
        bb.append(array.buffer);
        var jpeg = bb.getBlob("image/jpeg");
    }
    else if(e.name == "InvalidStateError"){
        // InvalidStateError (tested on FF13 WinXP)
        var jpeg = new Blob( [array.buffer], {type : "image/jpeg"});
    }
    else{
        // We're screwed, blob constructor unsupported entirely   
    }
}

Fiddle: http://jsfiddle.net/Jz8U3/13/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...