JS 通过后台接口返回的URL地址下载文件并保存到本地(已在项目中使用,保存音视频文件)


今天做antdV表格勾选下载操作时,因为粗心大意碰到了下载问题,特此记录~

一、单个文件下载逻辑代码如下:

const exportFile = (data, fileName, _this)=>{
 // 地址不存在时,禁止操作
  if(!data)return;
// 下载文件并保存到本地 const callback
= (data)=>{
   // 创建a标签,使用 html5 download 属性下载, const link
= document.createElement('a');
   // 创建url对象 const objectUrl
= window.URL.createObjectURL(new Blob([data])); link.style.display='none'; link.href=objectUrl;
   // 自定义文件名称,
fileName
   link.download = fileName;
   document.body.appendChild(link);
   link.click();
   // 适当释放url
window.URL.revokeObjectURL(objectUrl);
 };
// 把接口返回的url地址转换为 blob const xhr
= new XMLHttpRequest(); xhr.open('get', data, true); xhr.responseType = 'blob'; xhr.onload = ()=> {
   // 返回文件流,进行下载处理 callback(xhr.response); }; xhr.send(); // 不要忘记发送 };

//
ie和浏览器兼容模式会有问题,可以用下面代码调试。
 try{
    exportFile(); // 调用方式
  }catch(err){
    // 兼容模式下,IE
    const exportBlob = new Blob([data]);
    if (navigator.userAgent.indexOf('Trident') > -1) {
      window.navigator.msSaveBlob(data, fileName);
    } else {
      exportFile(); // 调用方式
    }
  };
  

调用方式:

exportFile('https://reading.oss.iyougu.com/uploads/mp/opus/1c5a8b6a391742cf93595d0a506b2d43.mp3', '测试.mp3');
exportFile('https://reading.oss.iyougu.com/uploads/mp/opus/2595f553407e471085de7f508afe5cb9.mp4', '测试.mp4');

  *表格数据有音频、视频文件,所以逻辑上区分了文件后缀名!

二、批量下载,压缩打包成zip:

  项目框架用的vue,已安装 axios,先安装依赖 jszip , file-saver;

    npm install jszip
    npm install file-saver

  

  主要业务代码如下:

  

    function filesToRar(arr, filename){
      const _this=this;
      const zip = new JSZip(); // 创建实例
      const cache = {}; // 记录压缩文件,不做实际用处
      const promiseArr = []; // 异步存储下载的二进制数据
      _this.$message.loading({ content: '正在加载压缩文件', key: 'filesRAR'}); // 结合antdv 组件提示
      const getFile = url => {
        url = url.replace('http://','https://'); // 根据域名有必要进行替换
        return new Promise((resolve, reject) => {
          axios({
            method:'get',
            url,
            responseType: 'arraybuffer'
          }).then(data => {
            resolve(data.data);
          }).catch(error => {
            reject(error.toString()); // 异常信息,暂不接收
          });
        });
      };
      for(const item of arr){
        const promise = getFile(item.yunUrl).then(res =>{
          const name = item.resName;
          const type = item.opusType === '视频'?'mp4':'mp3'; // 区分音视频链接,并重命名
          zip.file(`${name}.${type}`, res, { binary: true}); // 添加文件,res可以是File文件也可以是Blob二进制数据。
      // 或者zip.folder添加成文件夹
          cache[name]=res;
        });
        promiseArr.push(promise); // 追加数据
      }
      Promise.all(promiseArr).then(() => {
     // 生成zip文件 zip.generateAsync({ type:
'blob'}).then(content => { _this.$message.loading({ content: '正在压缩', key: 'filesRAR'}); FileSaver.saveAs(content, filename); // 生成二进制流,可以上传也可以存储。此处是浏览器打包并下载。 _this.$message.success({ content: '压缩完成', key: 'filesRAR'}); _this.isLoading = false; }); }).catch(err =>{ console.log(err); _this.isLoading = false; _this.$message.error('文件压缩失败'); }); }

调用方式:   filesToRar(arr, '文件.zip')  

注意:下载的文件是音视频文件,等待时间稍长,大家有什么好的解决办法吗?

 

 完成!o(* ̄▽ ̄*)ブ

如果您觉得有用的话给个推荐吧😊

有问题在评论区多多交流嗷~~

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM