Fetch API & arrayBuffer & Blob All In One


Fetch API & arrayBuffer & Blob All In One

const convertTypedArrayToBlobURL = (typedArray, mimeType) => {
  const blob = new Blob(
      [typedArray.buffer],
      {type: mimeType},
  );
  return {
     blob,
     url: URL.createObjectURL(blob),
  };
}

const bytes = new Uint8Array(59);
for(let i = 0; i < 59; i++) {
  bytes[i] = 32 + i;
}

// 生成 blob 和 url
const {url, blob} = convertTypedArrayToBlobURL(bytes, 'text/plain');

const reader = new FileReader();
reader.addEventListener('loadend', () => {
   // reader.result contains the contents of blob as a typed array
   console.log('reader.result =', reader.result);
});
// 还原 blob
reader.readAsArrayBuffer(blob);

// 还原 blob
const text = await (new Response(blob)).text();
text;
// ` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ`

// 还原 blob
const text = await blob.text();
text;
// ` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ`

blob.text();

arrayBuffer

function getData() {
  source = audioCtx.createBufferSource();
  var myRequest = new Request('viper.ogg');
  fetch(myRequest).then(function(response) {
    // promise.then(res => res.json()).catch(err => {}).finally(() => {});
    // ?  
    // promise.then(res => res.arrayBuffer()).catch(err => {}).finally(() => {});
    return response.arrayBuffer();
  }).then(function(buffer) {
    audioCtx.decodeAudioData(buffer, function(decodedData) {
      source.buffer = decodedData;
      source.connect(audioCtx.destination);
    });
  });
};

// wire up buttons to stop and play audio
play.onclick = function() {
  getData();
  source.start(0);
  play.setAttribute('disabled', 'disabled');
}

File / Blob

The Response() constructor accepts Files and Blobs, so it may be used to read a File into other formats.

function readFile(file) {
  return new Response(file).arrayBuffer();
}


https://developer.mozilla.org/en-US/docs/Web/API/Response/arrayBuffer

refs

https://javascript.info/blob

https://developer.mozilla.org/en-US/docs/Web/API/Blob


Flag Counter

?xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有??xgqfrms, 禁止转载 ???,侵权必究??!