java - 在 spring boot 中将响应下载为 POST 请求的文本文件

标签 java rest spring-boot http-post

我正在尝试使用 springBoot 中的 POST 请求的文本文件进行响应。虽然 GET 请求工作正常,并且当从 UI 发出 GET 请求时会下载文件。 以下是 POST 请求的请求 header :

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) 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

关于java - 在 spring boot 中将响应下载为 POST 请求的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50944115/

相关文章:

java - 是否可以有一个带有验证的表单并使用丰富的:modalPanel for data entry too?

Java调用同一个类的另一个方法中的一个方法

html - 是否应该在表单中使用 PUT 和 DELETE?

RESTful API URI 设计

java - 如何防止嵌入式netty服务器从spring-boot-starter-webflux启动?

java - 为什么耗时的测量是错误的?

Java:我可以将对象列表转换为字符串 [] 列表,反之亦然吗?

java - AWS-java.sql.SQLException : Access denied for user '' @'ip' (using password: YES)

c# - 套接字编程或 REST 服务

java - 注释不起作用之前的Spring AOP