我有基于Spring的休息网络服务来下载文档。我正面临着这项服务的奇怪问题。如果我直接从浏览器地址栏调用此休息服务,我可以下载具有正确字符的文档。但是,如果我从其他客户端/角度应用程序调用相同的休息服务,我会得到一些特殊字符,文档格式不正确。
以下是春假休息服务代码
@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<byte[]> downloadResume(HttpServletRequest request,
HttpServletResponse response,
@RequestParam(value = "id") String id)
throws Exception {
File file = new File("C:/resume.doc");
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
}
} catch (IOException ex) {
}
byte[] bytes = bos.toByteArray();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
httpHeaders.setContentLength(bytes.length);
httpHeaders.setContentDispositionFormData("attachment", "test");
return new ResponseEntity(bytes, httpHeaders, HttpStatus.OK);
}
以下是从其他客户端调用下载服务时使用的请求标头参数。
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:8080/dist/index.html
Cookie: _ga=GA1.1.1133600505.1423631305; _gat=1
Connection: keep-alive
更新 添加了下面的角度代码。但是,来自rest客户端的服务调用也存在同样的问题。
downloadFactory.download(id)
.then(function(response) {
var a = document.createElement("a");
document.body.appendChild(a);
var blob = new Blob([response.data], {type: "application/octet-stream"});
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'test';;
a.click();
window.URL.revokeObjectURL(url);
}, function(error) {
});