下列使用.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();
  });
}

打包下载

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();
      });
    }


参考:前端通过url下载文件时进行重命名(fileSaver部分源码解析)