Eve*_*0id 2 javascript java ajax jquery spring
我需要通过ajax从服务器下载文件.问题是该文件未存储在服务器上.我的基于java的后端自动从请求参数生成文件并在响应正文中返回它:
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void download(@RequestParam String description, @RequestParam Long logId, HttpServletResponse response) {
try {
InputStream fileContent = // getting file as byte stream
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("Content-Disposition", "attachment; filename=file.zip");
ServletOutputStream responseOutputStream = response.getOutputStream();
org.apache.commons.io.IOUtils.copy(fileContent, responseOutputStream);
response.flushBuffer();
} catch (IOException e) {
logger.error("Attempt to download file failed", e);
}
}
Run Code Online (Sandbox Code Playgroud)
所以我需要处理它并允许用户下载文件.我的客户端包含这个:
$.ajax({
type: "GET",
url: "/download",
data: {
description: "test",
logId: 123
},
success: function(data) {
var blob = new Blob([data]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "file.zip";
link.click();
}
})
Run Code Online (Sandbox Code Playgroud)
控制器返回文件,但没有任何反应.我究竟做错了什么?
不要进行AJAX调用,而是将窗口的href设置为指向用于下载文件的URL.然后更改响应的内容类型,并将响应application/x-download的标头设置为Content-disposition:
response.setContentType("application/x-download");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
response.flushBuffer();
function download(fileName) {
window.location.href = "/download?description=test&logId=123";
}
Run Code Online (Sandbox Code Playgroud)
另外,看看这个SO帖子,它解决了与你的问题类似的问题.
| 归档时间: |
|
| 查看次数: |
8578 次 |
| 最近记录: |