2011-04-22 47 views
5

我使用ExtJS为我的程序构建客户端。有一种情况是我想向服务器发送Ajax请求,并获取响应文件(二进制文件,而不是纯文本文件,即XLS或PDF)。我怎样才能通过ExtJS获得返回的文件(我的意思是这个文件可以下载并存储到客户端)?我无法使用var result = Ext.decode(response.responseText)来接收结果,因为响应包含二进制数据并且无法解码。获取响应文件的使用ExtJS

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(); 
    } 

太谢谢你了!

回答

2

如果您需要使用典型浏览器提供的打开/保存对话框提示用户,则不需要进行此调用AJAX。

只需从您的页面链接到myController/exportFile就足够了。
例如<a href="myController/exportFile">my file</a>

对于这种方法的工作,从myController/exportFile HTTP响应必须包括相应的头文件(即,内容类型和内容处置)告诉浏览器“这是文件显示打开/保存对话框”,并根据您的snippet,我看到你已经有这个照顾。

+0

很好的答案!你是最棒的 !!我已经找了很久,只有这个帖子给了我适当的答案! – davs 2011-07-28 12:47:57

+0

@amol你能帮我吗[这里](http://stackoverflow.com/questions/8505995/itextsharp-generated-pdf-how-to-prompt-a-user-to-choose-where-to-save) – Armance 2011-12-15 09:53:15

0

您可以将文件保存到服务器的文件系统和发送window.open(“HTTP://your.domain/your/file”)到客户端... 其中http://your.domain/your/file - 链接到文件

+0

window.open将失去对任何错误处理的控制,并非所有的浏览器客户端都允许window.open – 2014-05-09 08:35:22