js Blob & File API All In One
js Blob & File API 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();
Blob
const obj = {
name: 'xgqfrms',
};
const blob = new Blob([JSON.stringify(obj, null, 4)], {type : 'application/json'});
// XHR
const blob = new Blob(
// ['https://cdn.xgqfrms.xyz/HTML5/Blob/2022-04-07-sh.mp4'],
[xhr.response],
{type : 'video/mp4'},
);
const urlBlob = URL.createObjectURL(blob);
https://developer.mozilla.org/en-US/docs/Web/API/Blob
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
File API
https://www.w3.org/TR/FileAPI/
https://github.com/w3c/FileAPI/issues/
In the example below, different code blocks handle progress, error, and success conditions.
UTF-16
&FileReader
function startRead() {
// obtain input element through DOM
var file = document.getElementById('file').files[0];
if(file){
getAsText(file);
}
}
function getAsText(readFile) {
var reader = new FileReader();
// Read file into memory as UTF-16
reader.readAsText(readFile, "UTF-16");
// Handle progress, success, and errors
reader.onprogress = updateProgress;
reader.onload = loaded;
reader.onerror = errorHandler;
}
function updateProgress(evt) {
if (evt.lengthComputable) {
// evt.loaded and evt.total are ProgressEvent properties
var loaded = (evt.loaded / evt.total);
if (loaded < 1) {
// Increase the prog bar length
// style.width = (loaded * 200) + "px";
}
}
}
function loaded(evt) {
// Obtain the read file data
var fileString = evt.target.result;
// Handle UTF-16 file dump
if(utils.regexp.isChinese(fileString)) {
//Chinese Characters + Name validation
}
else {
// run other charset test
}
// xhr.send(fileString)
}
function errorHandler(evt) {
if(evt.target.error.name == "NotReadableError") {
// The file could not be read
}
}
refs
https://javascript.info/blob
https://codepen.io/xgqfrms/pen/xxpzGLY?editors=1010
?xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有??xgqfrms, 禁止转载 ???,侵权必究??!