将图像保存到Webkit和Gecko中的blob

save image to blob in webkit and gecko

本文关键字:Gecko 中的 blob Webkit 图像 保存      更新时间:2023-09-26

我需要通过ajax下载图像文件,将其保存到blob中,稍后显示在图像标签中。在我正在使用的网络工具包中

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,blob

大小为 43312。图像显示正确,到目前为止一切顺利。现在让我们转到壁虎:

首先,我卡在xhr.responseType = 'arraybuffer'上;出于某种原因,Firefox 只接受 'arrayBuffer' 而不接受 'arraybuffer'。这很令人困惑,因为根据 https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest?redirectlocale=en-US&redirectslug=DOM%2FXMLHttpRequest 的说法,壁虎也应该接受数组缓冲区。

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

好的,谜团解开了。

在 Firefox 中,你需要先做 xhr.open,然后你可以将 responseType 设置为 arraybuffer。