没有在服务器中保存文件,我无法通过Spring MVC中的Ajax下载文件
问题内容:
在一页中,有一个下载文件的链接,例如 \myapp\controller\file?id=45
在控制器中有
InputStream stream = null;
byte [] buffer =someService.getFile(somedata);
stream = new ByteArrayInputStream(buffer);
System.out.println("get file---");
response.addHeader("Content-Disposition","attachment; filename=report.pdf");
try {
IOUtils.copy(stream, response.getOutputStream());
System.out.println("get file---OK");
} catch (Exception e) {
e.printStackTrace();
}
这项工作正常,但在另一页
$.ajax({
type: 'POST',
url: '${url}',
data: {sdate: $('#date').val() },
success: function (data) {
alert(data)
},
error:function (xhr, ajaxOptions, thrownError) {
console.log("in error");
}
});
在控制台上曾经说过
获取文件-
获取文件-确定
但是浏览器什么也不做。
我添加了成功alert(data)
进行调试,它显示了PDF文件的二进制内容,例如:
%PDF-1.4% 3 0 obj <> streamx ͝O $ q )ޑ: U] E d A 1^ h ǃ \ nS X + RI J Y r F
?
现在,资源管理器如何理解要下载的文件?
由于缺少许可证,我无法保存服务器端的文件
问题答案:
您不能使用ajax下载文件。
无论使用
- jQuery ajax文件下载插件http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/
- 或在服务器端生成文件,然后使用ajax传递url并使用
window.location="fileName"