如何使用带有Node / Express后端的Angular 5 HttpClient get方法下载excel(xlsx)文件?

时间:2018-02-01 01:19:09

标签: node.js angular express filesaver.js

我在nodejs服务器上的目录中有一个excel文件 - 该文件的路径是 - ./api/uploads/appsecuritydesign/output/appsecdesign.xlsx

单击Angular 5组件中的按钮,我只是尝试使用FileSaver下载文件。

下面是我的Angular组件。

Angular Component with Download button

这里是Angular中按钮的模板代码,一旦点击就会调用saveFile()函数。

<a class="btn btn-primary" (click) = "saveFile()">Download</a>

这是saveFile()函数。

   saveFile(){

    console.log("In ToolInput Component: ", this.token); //Okta token
          console.log("In ToolInput Component: ", this.whatamidoing); //this variable has the server FilePath

this.fileService.getappsecdesignfile(this.token, this.whatamidoing).subscribe(res => {
            let blobtool5 = new Blob([res], { type: 'application/vnd.ms-excel;charset=utf-8' });
            FileSaver.saveAs(blobtool5, 'Application_Security_Design.xlsx');
          },
          (err: HttpErrorResponse) => {
            if (err.error instanceof Error) {

                  console.log('An error occurred:', err.error.message);
                  console.log('Status', err.status);
                } else {
                  console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
                  console.log('Status', err.status);
                }
          });
    }

此时我在浏览器中检查了console.log。他们正是他们应该是的。所以我将正确的文件路径和令牌传递给我的fileService中的getappsecdesignfile方法。

enter image description here

现在让我们看看我的fileService中的getappsecdesignfile方法。

getappsecdesignfile ( token, tool5filepath ) : Observable<any>{

       console.log("In Service tool5filepath: ", tool5filepath);
       console.log("In Service token", token);
       console.log("In Service GET url: ", this.getappsecdesignfileurl);

       //Since the tool5filepath has / (slashes etc) I am encoding it below.

       let encodedtool5filepath = encodeURIComponent(tool5filepath);
       console.log('Encoded File Path: ', encodedtool5filepath);

       let req = new HttpRequest('GET', this.getappsecdesignfileurl,{params: new HttpParams().set('path', encodedtool5filepath)},{headers: new HttpHeaders().set('Accept', 'application/vnd.ms-excel').set('Authorization', token)});
       console.log(req);
       return this.http.request(req);

   }

这就是fileService方法的全部内容。让我们从浏览器中查看此方法的console.logs,以确保设置所有正确的值。

enter image description here

现在让我们在进入服务器部分之前先看看请求本身。

enter image description here

就我而言,标题设置正确,参数设置正确。我看到的两个问题是Angular的拦截器可能设置了responseType:json并在我的请求中添加了一个param op:s。

节点/ Express服务器代码。

app.get('/getappsecdesignfile', function(req, res){
console.log("In get method app security design");
    accessTokenString = req.headers.authorization;
    console.log("Okta Auth Token:", accessTokenString);

    console.log("Tool5 File Path from received from Angular: ", req.query.path); //this is where the server console logs shows Tool5 File Path after decoding: ./undefined

    oktaJwtVerifier.verifyAccessToken(accessTokenString)
    .then(jwt => {
    // the token is valid
      console.log(jwt.claims);

      res.setHeader('Content-Disposition', 'attachment; filename= + Application_Security_Design.xlsx');
      res.setHeader('Content-Type', 'application/vnd.ms-excel');

      let tool5filepath = './' + decodeURIComponent(req.query.path);
      console.log("Tool5 File Path after decoding: ", tool5filepath);
      res.download(tool5filepath);

      }).catch(err => {
        // a validation failed, inspect the error
        res.json({success : false, message : 'Authorization error.'});
      });
    });

如果我使用Postman,api工作正常。然而,在Angular to Node通信之间的某些地方发生了一些我不理解的事情。

以下是服务器记录的内容。 (大问题如何变得不确定)?

Tool5 File Path from received from Angular:  undefined
Tool5 File Path after decoding:  ./undefined
Error: ENOENT: no such file or directory, stat '<dirpath>/undefined'

以下是我在浏览器日志中看到的内容:

zone.js:2933 GET http://localhost:3000/getappsecdesignfile 404 (Not Found)
toolinput.component.ts:137 Backend returned code 404, body was: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Error: ENOENT: no such file or directory, stat &#39;<dirpath>/undefined&#39;</pre>
</body>
</html>

然后浏览器下载一个损坏且无法打开的xlsx文件。

我已检查文件位于目录中并准备下载。

enter image description here

感谢您提供有助于我解决此问题的任何提示。

1 个答案:

答案 0 :(得分:3)

终于明白了。

2个具体的变化使这项工作成功。

更改#1 - 设置responseType:&#39; blob&#39;首先定义params和header然后在http.get中使用它们。 (http只是来自angular / common / http的HttpClient类型的对象,它已被注入到服务类中。

getappsecdesignfile ( token, tool5filepath ) : Observable<any>{

       console.log("In Service tool5filepath: ", tool5filepath);
       console.log("In Service token", token);
       console.log("In Service GET url: ", this.getappsecdesignfileurl);

       let encodedtool5filepath = encodeURIComponent(tool5filepath);
       console.log('Encoded File Path: ', encodedtool5filepath);

       let getfileparams = new HttpParams().set('filepath', encodedtool5filepath);
       let getfileheaders = new HttpHeaders().set('Accept', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').set('Authorization', token);

       return this.http.get(this.getappsecdesignfileurl, {responseType: 'blob', params: getfileparams, headers: getfileheaders});
   }

更改#2 - 组件代码 - FileSaver。出于某种原因输入:&#39; application / vnd.ms-excel&#39;在FileSaver中无法正常工作。这里的res只是来自http.get调用的响应。

let blobtool5 = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
FileSaver.saveAs(blobtool5, 'Application_Security_Design.xlsx');