首页 > 解决方案 > 下载 .exe 文件在 Angular 前端出现错误

问题描述

我在节点 JS 中使用它:-

let file = `${process.cwd()}/server/downloads/JRuler.exe`;
   let filename = path.basename(file);
   let stat = fs.statSync(file);

   res.writeHead(200, {
       'Content-Type': 'application/octet-stream',
       'Content-Length': stat.size,
       'Content-disposition': 'attachment; filename=' + filename
   });

   let readStream = fs.createReadStream(file);
   readStream.pipe(res);

这是在 Angular

  download() {
    this.clientAPI.get(Endpoints.DOWNLOAD).toPromise()
    .then(res => {
      console.log('res')
      let blob = new Blob([new Uint8Array(res.file)],{type:'application/octet-stream'});
      console.log('blob',blob);
      let a = document.createElement('a');
      var ua=navigator.userAgent;
      var msie= ua.indexOf("MSIE") > -1 || ua.indexOf("Trident/") > -1;
      if(msie){
        navigator.msSaveOrOpenBlob(blob,res.filename);
      }
      else{
      a.href = (URL.createObjectURL(blob));
      a.download = res.filename;
      document.body.appendChild(a);
      a.click();
      a.remove();
      }
    })
    .catch(err => console.error("download error = ", err))
  }

但我得到了错误: - 在此处输入图像描述

请建议我如何在角度前端处理。

标签: node.jsangularexpress

解决方案


http 客户端需要 responseType blob 才能知道如何解析响应并在您的情况下返回订阅者或承诺。

 download() {
        this.clientAPI.get(Endpoints.DOWNLOAD, {responseType: 'blob'}).toPromise()
        .then(res => {
          console.log('res')
          let blob = new Blob([new Uint8Array(res.file)],{type:'application/octet-stream'});
          console.log('blob',blob);
          let a = document.createElement('a');
          var ua=navigator.userAgent;
          var msie= ua.indexOf("MSIE") > -1 || ua.indexOf("Trident/") > -1;
          if(msie){
            navigator.msSaveOrOpenBlob(blob,res.filename);
          }
          else{
          a.href = (URL.createObjectURL(blob));
          a.download = res.filename;
          document.body.appendChild(a);
          a.click();
          a.remove();
          }
        })
        .catch(err => console.error("download error = ", err))
      }

推荐阅读