javascript – Blob和Blobbuilder或Blobbuilder在Android原生浏览器上的问题有什么区别

前端之家收集整理的这篇文章主要介绍了javascript – Blob和Blobbuilder或Blobbuilder在Android原生浏览器上的问题有什么区别前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
问题不是从 What’s the difference between BlobBuilder and the new Blob constructor?重复

我正在做网络应用程序.要上传图像我使用Blob,以防万一BlobBuilder. Blob运行良好,但Blob不适用于Android原生浏览器,Android原生浏览器使用BlobBuilder.我预计,Blob和BlobBuilder返回相同的blob,但他们没有.这是我的代码

base64toBlob: function(b64Data,contentType,sliceSize) {
  var BlobBuilder,blob,byteArray,byteCharacters,byteNumbers,charCodeFromCharacter,err,posIndex;

  if (contentType == null) {
    contentType = '';
  }
  if (sliceSize == null) {
    sliceSize = 1024;
  }
  posIndex = b64Data.indexOf('base64,');
  if (posIndex !== -1) {
    b64Data = b64Data.substring(posIndex + 7);
  }
  charCodeFromCharacter = function(c) {
    return c.charCodeAt(0);
  };
  byteCharacters = atob(b64Data.replace(/\s/g,''));
  byteNumbers = Array.prototype.map.call(byteCharacters,charCodeFromCharacter);
  byteArray = new Uint8Array(byteNumbers);
  try {
    blob = new Blob([byteArray.buffer],{
      type: contentType
    });
    return blob;
  } catch (_error) {
    err = _error;
    BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
    blob = new BlobBuilder();
    blob.append(byteArray.buffer);
    return blob.getBlob(contentType);
  }
}

我发送请求时做了日志

blobImg = base64toBlob(base64Data,imageType);
alert(JSON.stringify(blobImg));
// alert shows {"type": "image/jpeg","size": 10251 } when blob worked
// alert shows {"type": "image/jpeg","size": 27822 } when blobbuilder worked
ajaxRequest.send(blobImg);

我尝试在所有浏览器上以相同的图像上传.在Chrome和其他浏览器上,我从log {“type”:“image / jpeg”,“size”:10251}获取并请求发送成功,但在Android原生浏览器上我得到{“type”:“image / jpeg”,“大小“:27822}并且请求失败,状态码为0.在android浏览器上工作catch部分(我猜,这意味着Android本机浏览器不支持Blob)我在android 4.1.2中测试过.我从谷歌没有发现任何问题.我很高兴如果有人帮助我!

解决方法

注意你传入的内容之间的区别:
try {
    blob = new Blob([byteArray.buffer],{ // use of .buffer
      type: contentType
    });
    return blob;
} catch (_error) {
    err = _error;
    BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
    blob = new BlobBuilder();
    blob.append(byteArray); // just uses the raw array
    return blob.getBlob(contentType);
}

MDN documentation开始BlobBuilder.append:

Appends the contents of the specified JavaScript object to the Blob
being built. If the value you specify isn’t a Blob,ArrayBuffer,or
String,the value is coerced to a string before being appended to the
blob.

byteArray不是ArrayBuffer类型,所以它可能被强制转换为字符串.您可以通过将其转换为字符串并检查其长度来自行确认.要修复它,只需在catch块中使用byteArray.buffer.

有趣的是,Blob constructor 似乎直接接受了一个ArrayBufferView,你的Uint8Array就是这个.这可能意味着你在这种情况下实际上并不需要.buffer,尽管我对API的熟悉程度不够高.

猜你在找的JavaScript相关文章