场景
2023年03月23日
一、分片上传
File
对象是特殊类型的 Blob
,且可以用在任意的 Blob
类型的上下文中。所以针对大文件传输的场景,我们可以使用 slice
方法对大文件进行切割,然后分片进行上传
const file = new File(["a".repeat(1000000)], "test.txt");
const chunkSize = 40000;
const url = "https://httpbin.org/post";
async function chunkedUpload() {
for (let start = 0; start < file.size; start += chunkSize) {
const chunk = file.slice(start, start + chunkSize + 1);
const fd = new FormData();
fd.append("data", chunk);
await fetch(url, { method: "post", body: fd }).then((res) =>
res.text()
);
}
}
二、文件下载
function download(fileName,blob){
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = fileName;
link.click();
link.remove();
URL.revokeObjectURL(link.href);
}
function handleClick(){
const fileName = 'blob.txt';
const blob = new Blob(["有的人活着他已经死了"],{type:"text/plain"});
download(fileName,blob);
}
三、blob 数据转化为 blob 格式地址
const str = '这是一个很寂寞的天,下着有些伤心的雨!';
const blob = new Blob([str], {
type: 'text/plain'
});
const blobUrl = URL.createObjectURL(blob);
console.log("blobUrl",blobUrl)
四、blob 数据转化为 base64 格式地址
const str = '这是一个很寂寞的天,下着有些伤心的雨!';
const blob = new Blob([str], {
type: 'text/plain'
});
const fileReader = new FileReader();
fileReader.onload = e => {
console.log("e.target.result",e.target.result)
};
fileReader.readAsDataURL(blob);
fileReader.onerror = () => {
console.log("错误")
};
五、type: 'video/webm'
格式地址转换为 type: 'video/mp4'
格式地址
const video = document.querySelector('video');
const url = 'http://127.0.0.1:5502/test/html/assets/video1.mp4';
const getVideoWebmBlobUrl = async url => {
const response = await fetch(url);
const arrayBuffer = await response.arrayBuffer();
const blob = new Blob([arrayBuffer], { type: 'video/webm' });
window.URL = window.URL || window.webkitURL;
const blobUrl = window.URL.createObjectURL(blob);
return blobUrl;
};
const transformOfWebmToMp4Blob = async url => {
const response = await fetch(url);
const arrayBuffer = await response.arrayBuffer();
const blob = new Blob([arrayBuffer], { type: 'video/mp4' });
window.URL = window.URL || window.webkitURL;
const blobUrl = window.URL.createObjectURL(blob);
return blobUrl;
};
const run = async () => {
let blobUrl = await getVideoWebmBlobUrl(url);
blobUrl = await transformOfWebmToMp4Blob(blobUrl);
video.src = blobUrl;
};
run();