我使用ExtJS为我的程序构建客户端。有一种情况是,我想发送一个Ajax请求到服务器,并获得响应文件(二进制文件,而不是纯文本文件,即XLS或PDF)。如何通过ExtJS获取返回文件(我的意思是该文件可以下载并存储到客户端)?我不能使用var result = Ext.decode(response.responseText)
接收结果,因为reponse包含二进制数据,并且无法解码。
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();
}
非常感谢!
发布于 2011-04-23 00:07:22
如果您需要通过浏览器提供的典型打开/保存对话框来提示用户,则无需进行此AJAX调用。
只要从你的页面链接到myController/exportFile
就足够了。
例如<a href="myController/exportFile">my file</a>
为了使这种方法起作用,来自myController/exportFile
的HTTP响应必须包括适当的头部(即Content-type和Content-disposition),这些头部告诉浏览器"this is file.show open/save dialog“,根据您的代码片段,我知道您已经处理好了这一点。
发布于 2011-04-22 17:40:34
你可以将你的文件保存到服务器的文件系统中,并将window.open('http://your.domain/your/file')发送到客户端...http://your.domain/your/file -link到文件的位置
https://stackoverflow.com/questions/5753811
复制相似问题