我正在尝试使用 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!");
}
);
对于支持有用的链接:
关于java - 在 spring boot 中将响应下载为 POST 请求的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50944115/