下载文件实例

let key = GuidUtil.getNewGUIDString().toString();
let token = res.data;
var xhr = new XMLHttpRequest();
//GET请求,请求路径url,async(是否异步)
xhr.open('GET', `${process.env.VUE_APP_API_BASE_URL}${path}`, true);
//设置请求头参数的方式,如果没有可忽略此行代码
xhr.setRequestHeader("Token", token);
//设置响应类型为 blob
xhr.responseType = 'blob';
// 进度条
xhr.onprogress = function(e) {
  <!--notification.open({-->
  <!--  key,-->
  <!--  message: '下载文件',-->
  <!--  description: name,-->
  <!--  icon: () => h(Progress, { type:"circle", percent: parseInt((e.loaded / e.total * 100).toFixed()), width: 40 }),-->
  <!--  duration: 0-->
  <!--});-->
}
//关键部分
xhr.onload = function (_e) {
  //如果请求执行成功
  if (this.status == 200) {
    var blob = this.response;
    var filename = name;//如123.xls
    var a = document.createElement('a');
    // blob.type = "application/octet-stream";
    //创键临时url对象
    var url = URL.createObjectURL(blob);

    <!--notification.open({-->
    <!--  key,-->
    <!--  message: '下载文件',-->
    <!--  description: name,-->
    <!--  icon: () => h(Progress, { type:"circle", percent:100, width:40 }),-->
    <!--  duration: 4.5-->
    <!--});-->

    a.href = url;
    a.download=filename;
    a.click();
    //释放之前创建的URL对象
    window.URL.revokeObjectURL(url);
  }
};
//发送请求
xhr.send();
最后修改:2023 年 04 月 27 日
如果觉得我的文章对你有用,请随意赞赏