我无法通过AJAX下载文件Spring MVC中不保存文件服务器 [英] I can not download file via ajax in spring mvc without save file in server
问题描述
在一个页面上有一个链接,下载喜欢文件\ MyApp的\控制器\文件吗?ID = 45
In a one page a have a link to download a file like \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();
}
这个工作做好了,但在另一页
This work well, but in another page
$.ajax({
type: 'POST',
url: '${url}',
data: {sdate: $('#date').val() },
success: function (data) {
alert(data)
},
error:function (xhr, ajaxOptions, thrownError) {
console.log("in error");
}
});
在控制台曾经说过,
获取文件---
获取文件---确定
但是浏览器不执行任何操作。
我添加的更迭警报(数据)
来调试,它显示PDF文件的二进制内容,如:
I add in succes alert(data)
to debug, it shows the binary content of PDF file like:
%PDF-1.4%,3 0 OBJ<>流x ͝O $ q )ޑ: U] E d A 1^h ǃ\nS # ? X+ RI J Y r F ?
%PDF-1.4 %���� 3 0 obj <>stream x�͝O�$�q���)ޑ:��U]���E�d�A��1^h��ǃ\nS��#��������?���X+��RI��J����Y�r��F�?
现在,如何探险家不解的是要下载的文件?
Now, how explorer understand is a file to download?
由于缺乏允许,我无法保存文件服务器端
推荐答案
您不能使用AJAX来下载文件。
You can't use ajax to download files.
或者使用
- 在jQuery的AJAX的文件下载插件<一href="http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/" rel="nofollow">http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/
- 或生成服务器端的文件中使用AJAX通过URL和
使用
了window.location =文件名
- Jquery ajax file download plugin http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/
- or generate the file on server side pass the url using ajax and
use
window.location="fileName"
这篇关于我无法通过AJAX下载文件Spring MVC中不保存文件服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!