JavaScript实现文件下载,打包下载和压缩包解压
下列使用.webm音频文件进行举例:
文件下载
npm下载file-saver
npm install file-saver
代码:
import { saveAs } from "file-saver";
async function downloadAudio(src: string, name: string) {
const blob = await getBlob(src);
saveAs(blob, name + ".webm");
}
function getBlob(url: string): Promise<Blob> {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
}
};
xhr.send();
});
}
//或者使用axios
async function getBlob(url: string): Promise<Blob> {
return new Promise(resolve => {
axios.get(url, { responseType: "blob" }).then(resp => resolve(resp.data));
});
}
打包下载
npm install jszip
函数
import JSZip from "jszip";
import { saveAs } from "file-saver";
//data=[{name:xx, ..., src:"blob:xxx"}{...}]
downAllRecord(data: any) {
let zip = new JSZip();//初始化
for (let i = 0; i < data.length; i++) {
let obj = data[i];
zip.file(obj.name + ".webm", getBlob(obj.src));
}
zip.generateAsync({ type: "blob" }).then(function(content: Blob) {
//使用blob下载zip
saveAs(content, "Sound.zip");
//这里也可以写成使用File下载zip,把blob转换为File
const filesZip = new File([content], "Sound.zip", { type: "application/zip" });
saveAs(filesZip);
});
}
function getBlob(url: string): Promise<Blob> {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
}
};
xhr.send();
});
}
压缩包解压
压缩包解压同样使用的是jszip
const unzipFile = async (url: string) => {
const zipFile = (await axios.get(url, { responseType: "blob" })).data;//以blob形式获取zip文件
return new Promise<any>(async resolve => {
var zipInit = new JSZip();
const zip = await zipInit.loadAsync(zipFile);//读取zip文件
const files = zip.files;
let zipFiles = {} as { [id: string]: ArrayBuffer };
const promises = _.map(Object.values(files), async value => {
const audioWavName = value.name;
const audioWav = await value.async("arraybuffer");//以arraybuffer的形式获得内容(我这里是获取音频文件)
zipFiles[audioWavName] = audioWav;
});
await Promise.all(promises);//使用Promise.all等待所有解压完成
resolve(zipFiles);
});
};