在Spring Boot中将响应下载为文本文件以用于POST请求

时间:2018-06-20 08:53:57

标签: java rest spring-boot http-post

我正在尝试使用springBoot中的POST请求文本文件进行响应。尽管从UI发出GET请求后,GET请求工作正常,并且下载了文件。 以下是POST请求的请求标头:

POST /smartedge/aoip/exportYaml HTTP/1.1
Host: localhost:9000
Connection: keep-alive
Content-Length: 121
Accept: application/json, text/plain, */*
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36
Content-Type: application/json
Referer: http://localhost:4200/dashboard/deploymentConfiguration
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,hi;q=0.8

这是响应标题:

HTTP/1.1 200
Access-Control-Allow-Origin: http://localhost:4200
Vary: Origin
Access-Control-Allow-Credentials: true
Content-Disposition: attachment; filename=baseConfig
Content-Type: text/plain;charset=UTF-8
Content-Length: 2473
Date: Wed, 20 Jun 2018 08:41:38 GMT

这是spring boot服务代码:

@ResponseBody
    @RequestMapping(value = "/exportYaml", method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
    public String previewYamlUpdated(@RequestBody JSONObject requestBean,HttpServletResponse response) {
String inputFilePath=null;
        String file=null;
        String fileName=requestBean.getString("fileName");
        response.setContentType("text/plain");
         response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            String content = "This is txt content";
            return content;
}

如何强制浏览器将响应下载为文本文件以用于POST请求?

1 个答案:

答案 0 :(得分:1)

花了几个小时,找到了解决该问题的方法:

1)xhr请求不允许立即下载文件。

解决方案实现如下:

downloadNewFile(data: Response){
    console.log("response is :");
    console.log(JSON.parse(JSON.stringify(data))._body);
   var a:any = document.createElement("a");
   document.body.appendChild(a);
   a.style = "display: none";

   var blob = new Blob([JSON.parse(JSON.stringify(data))._body], { type: 'octet/stream' });
   var url= window.URL.createObjectURL(blob);
   a.href = url;
   a.download = "download.txt";
   a.click();
   window.URL.revokeObjectURL(url);

 } 

this._http
      .get(this.baseUrl + "/deployments/get/all")
      .map(res => res = res.json())
      .subscribe(
      data => {
        this.downloadNewFile(data);
      },
      error => {
        this.ngxtoastr.error("Server Error!");
      }
      );

有关支持的有用链接:

How do I download a file with Angular2