Kimchy
Kimchy

Reputation: 501

download response as text file for POST request in spring boot

I am trying to respond with a text file for POST request in springBoot. Although GET request works ok and a file gets downloaded when GET request is made from UI. Below is request header for a POST request as :

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

Here is the response Header:

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

Here is spring boot service code:

@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;
}

How do force the browser to download response as a text file for a POST request??

Upvotes: 2

Views: 3516

Answers (1)

Kimchy
Kimchy

Reputation: 501

Spent a few hrs and found a solution to the issue:

1) xhr request does not allow file download straight away.

Solution implemented as below:

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!");
      }
      );

For support helpful link:

How do I download a file with Angular2

Upvotes: 1

Related Questions