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 acceptsFile
s andBlob
s, 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://developer.mozilla.org/en-US/docs/Web/API/Blob
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16132038.html
未经授权禁止转载,违者必究!