【问题标题】:Get response file use ExtJS使用 ExtJS 获取响应文件
【发布时间】:2011-04-22 08:49:22
【问题描述】:

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

非常感谢!

【问题讨论】:

    标签: file extjs response


    【解决方案1】:

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

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

    要使这种方法起作用,来自myController/exportFile 的 HTTP 响应必须包含适当的标头(即 Content-type 和 Content-disposition),告诉浏览器“这是文件。显示打开/保存对话框”并根据您的sn-p,我看到你已经处理好了。

    【讨论】:

    • 很好的答案!你是最棒的 !!找了这么久,只有这个帖子给了我正确的答案!
    • @amol 你能帮我吗here
    【解决方案2】:

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

    【讨论】:

    • window.open 将失去对任何错误处理的控制,并非所有浏览器客户端都允许 window.open
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 2018-04-15
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    相关资源
    最近更新 更多