boreguo

1、HTML5新特性

 <a href="要下载文件的路径"  download="要下载文件的名称"></a>

2、下载方法

    window.open(\'文件路径\');

 或  window.location.href = \'文件路径\';

(打开新页面造成页面一闪一闪的)

问题:以上两种方式在批量下载时循环不可用,在循环中只执行循环的最后一次操作(当然,如果单次下载,点击速度过快也会仅下载最后一次点击的文件)。

解决:使用iframe下载

3、下载方法

download(item, url) {
  const iframe = document.createElement("iframe");
  iframe.style.display = "none"; // 防止影响页面
  iframe.style.height = \'0px\'; // 防止影响页面
  iframe.src = url+\'?downloadUrl=\'+item.fileUrl+\'&fileName=\'+item.fileName;
  document.body.appendChild(iframe); // 这一行必须,iframe挂在到dom树上才会发请求
  // 5分钟之后删除(onload方法对于下载链接不起作用)
  setTimeout(()=>{
    iframe.remove();
  }, 5 * 60 * 1000);
}
-------------------------------------------------------------------------------------------------
this.selectFiles.forEach(it => {
  that.download(it, url);
})

 

4、解决文件名为中文下载出现_____.doc的问题(angular中)

download() {
let url = `路径`;
this.http.request(\'GET\',url,{
responseType: "arraybuffer"
}).subscribe((val:any)=>{
let blob = new Blob([val], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
let objectUrl = URL.createObjectURL(blob);
let filename = \'文件名\';
let aDownload = $("<a><span class=\'downloadFile\'></span></a>").attr("href",objectUrl).attr(\'download\',filename);
$("body").append(aDownload);
$(".downloadFile").click();
aDownload.remove();
});
}

5、下载文件流


downloadFile(data,type) {
    // 下载类型 xls
    const contentType = \'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\';
    // 下载类型:csv
    const contentType2 = \'text/csv\';
    const blob = new Blob([data], { type: contentType });
    const url = window.URL.createObjectURL(blob);
    // 打开新窗口方式进行下载
    //window.open(url); 
  
    // 以动态创建a标签进行下载
    const a = document.createElement(\'a\');
    let fileName = "下载数据"+new Date().getTime();
    a.href = url;
    a.download = fileName + \'.xls\';
    a.click();
    window.URL.revokeObjectURL(url);
  }
-----------------------------------------------------------------------------------------------------------
上传的时候加{responseType: \'arraybuffer\'}
this.http.post(`url`,formData, {responseType: \'arraybuffer\'})...
 

分类:

技术点:

相关文章: