在webkit和gecko中将图像保存为blob

时间:2013-10-02 00:23:47

标签: javascript webkit xmlhttprequest blob gecko

我需要通过ajax下载图像文件,将其保存为blob,然后显示在图像标记中。在webkit中我正在使用

var xhr = new XMLHttpRequest();
var imgSrc = "test.jpg";
xhr.responseType = 'arraybuffer';
xhr.open("GET", imgSrc, true);
xhr.onload = function (oEvent) {
  console.log('onload1');
  var blob = new Blob([xhr.response], {type: "image/jpg"});
  console.log(blob.size);
  var img = document.createElement('img');
  img.onload = function() {
    console.log('onload2');
    document.body.appendChild(img);
  }
  img.onerror = function() {
    console.log('error');
  }
  img.src = webkitURL.createObjectURL(blob);
}
xhr.send(null);

图像尺寸为43312,斑点尺寸为43312.图像显示正确,到目前为止一直很好。现在让我们转向壁虎:

首先,我被困在xhr.responseType ='arraybuffer';出于某种原因,firefox只接受'arrayBuffer'而不接受'arraybuffer'。这很令人困惑,因为根据https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest?redirectlocale=en-US&redirectslug=DOM%2FXMLHttpRequest,gecko也应该接受arraybuffer。

然后我用URL替换webkitURL。下载图像,创建blob,但大小为77978,图像丢失失败(显然图像数据已损坏)。

1 个答案:

答案 0 :(得分:0)

好的,神秘解决了。

在firefox中,您需要先执行xhr.open,然后才能将responseType设置为arraybuffer。