使用 ExtJS 获取响应文件 [英] Get response file use ExtJS
问题描述
我使用 ExtJS 为我的程序构建客户端.有一种情况,我想向服务器发送 Ajax 请求,并获取响应文件(二进制文件,而不是纯文本文件,即 XLS 或 PDF).如何通过 ExtJS 获取返回的文件(我的意思是该文件可以下载并存储到客户端)?我无法使用 var result = Ext.decode(response.responseText)
来接收结果,因为响应包含二进制数据并且无法解码.
I use ExtJS to build the client-side for my program. There's a situation that I want to send an Ajax request to server, and get the response file (binary file, not plain text file, i.e XLS or PDF). How can I get that returned file by ExtJS (I mean that file can be downloaded and stored to client)? I cannot use var result = Ext.decode(response.responseText)
to receive the result because reponse contains binary data and it cannot be decoded.
Ajax 调用非常简单:
The Ajax call is very simple :
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!')
}
});
这是我返回文件的服务器操作:
Here is my server action to return file:
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.
If you need the user to be prompted with the typical browser provided open/save dialog box, you don't need to make this call AJAX.
只需从您的页面链接到 myController/exportFile
就足够了.
例如我的文件
Just linking to myController/exportFile
from your page should be enough.
e.g. <a href="myController/exportFile">my file</a>
为了使这种方法起作用,来自 myController/exportFile
的 HTTP 响应必须包含适当的标头(即 Content-type 和 Content-disposition),告诉浏览器这是文件.show open/保存对话框"并根据您的代码段,我看到您已经处理了这个问题.
For this approach to work, HTTP response from myController/exportFile
must include the appropriate headers (namely, Content-type and Content-disposition) that tell the browser "this is file. show open/save dialog" and based on your snippet, I see that you already have this taken care of.
这篇关于使用 ExtJS 获取响应文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!