获取响应文件使用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
即可。例如
< a href =myController / exportFile>我的文件< / a>
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 / save对话框,并根据您的代码段,我看到您已经有这样的照顾。
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屋!