从rest webservices spring下载文件

时间:2017-08-18 09:02:46

标签: java angular rest

我试图下载任何调用我的其余网络服务的文件。我使用spring + jersey作为Web服务,使用Angular 2作为前端。 因此,当我在前面碰撞时,webservices获取我的文件,但是下载它的窗口没有显示。

我的其余API:

Label.config(text='*label's text*')

My Angular服务:

    @POST
    @Path("/download")
    @ApiOperation(value = "Download")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response downloadFile(@ApiParam(value = "File", required = true) String filePath) {
        File file = new File("/webapps/pdf/upload/msg/1/gest.PNG");
        Response.ResponseBuilder response = Response.ok((Object) file);
        try {
            String contentType = Files.probeContentType(file.toPath());
            response.header("Content-Disposition", "attachment; filename="+file.getName());
            response.header("Content-Type", contentType);
            return response.build();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

My Angular组件:

    downloadFile(path) {
      const headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded', 'Accept': '*'});
      const options = new RequestOptions({headers: headers});

      options.responseType = ResponseContentType.Blob;
      return this.http.post(apiUrl + "msg/download", path, options)
      .catch(this.handleError);
  }

Html:

  downloadFile(documentPath) {
    this.msgService.downloadFile(documentPath).subscribe(response => {
      var contentType = response.headers('Content-Type');
      let url = window.URL.createObjectURL(new Blob([response._body], {type: contentType}));
      window.open(url);    
      });
  }

当我点击我的<figure class="ui-g-12 " *ngFor="let document of msg.documents_path" (click)="downloadFile(document)"> <img [src]="selectImageByExtension(document.split('.').pop().toLowerCase())" /> <figcaption>{{document.split('/').pop().toLowerCase()}}</figcaption> </figure> 时,我可以看到文件很好: enter image description here

但是什么都没弹出来。 我错过了什么 ?

1 个答案:

答案 0 :(得分:0)

因此,唯一适用于我的解决方案是使用GET请求而不是POST将文件路径作为路径参数传递。

Rest API:

    @GET
    @Path("/download/{filePath}")

    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response getdownloadFile(@PathParam("filePath") String filePath) {
        String path = null;

            byte [] barr = Base64.getDecoder().decode(filePath);
            path = new String(barr);
        File file = new File(path);
        try {
            String contentType = Files.probeContentType(file.toPath());

            Response.ResponseBuilder response = Response.ok((Object) file);
            response.header("Content-Disposition", "attachment; filename="+file.getName());
            response.header("Content-Type", contentType);
            response.header("Content-Length", file.length());
            return response.build();
        } catch (IOException e) {
            e.printStackTrace();
            return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
        }
    }

角度服务:

    downloadFile(path) {
    const headers = new Headers({'Content-Type': 'text/plain', 'Accept': '*'});
    const options = new RequestOptions({headers: headers});
    options.responseType = ResponseContentType.Blob;
    return this.http.get(apiUrl + "msg/download/"+btoa(path), options)
      .map(res => res)
      .catch(this.handleError);
  }

角度组件:

  downloadFile(documentPath) {
    this.msgService.downloadFile(documentPath).subscribe(response => {
        let params = documentPath.split('/' );
        var blob = new Blob([response._body]);
        FileSaver.saveAs(blob, params[params.length-1]);
      });
  }