我使用 ExtJS 为我的程序构建客户端。有一种情况,我想向服务器发送 Ajax 请求,并获取响应文件(二进制文件,而不是纯文本文件,即 XLS 或 PDF)。我如何获取 ExtJS 返回的文件(我的意思是该文件可以下载并存储到客户端)?我无法使用var result = Ext.decode(response.responseText)
接收结果,因为响应包含二进制数据并且无法解码。
Ajax 调用非常简单:
Ext.Ajax.request({
url : 'myController/exportFile',
method : 'GET',
success : function(response, opts) {
// What should I do to get the file?
},
failure : function(response, opts) {
alert('Export file failed!')
}
});
这是我返回文件的服务器操作:
public void sendFile(HttpServletResponse response, String filePath) {
def file = new File(filePath);
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=${file.getName()}");
response.outputStream << file.newInputStream();
}
太感谢了!
如果您需要使用典型浏览器提供的打开/保存对话框来提示用户,则不需要进行此调用 AJAX。
只是链接到myController/exportFile
从你的页面应该足够了。
e.g. <a href="myController/exportFile">my file</a>
为了使这种方法发挥作用,来自的 HTTP 响应myController/exportFile
必须包含适当的标头(即 Content-type 和 Content-disposition),告诉浏览器“这是文件。显示打开/保存对话框”,并且根据您的代码片段,我发现您已经处理了这个问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)