如何强制浏览器打开“另存为”对话框进行二进制响应?

时间:2013-05-02 07:49:05

标签: javascript http zimbra

我正在开发Zimbra Zimlet。 我正在从Javascript请求JSP(两者都属于同一个Zimlet)

var jspUrl = this.getResource("my.jsp");
var callback = new AjxCallback(this, this._rpcCallback, ["param1", "param2"]);
AjxRpc.invoke(null, jspUrl, null, callback, true);

_rpcCallback 功能

automator_HandlerObject.prototype._rpcCallback = function(p1, p2, response) {
    if (response.success == true) {
        appCtxt.getAppController().setStatusMsg(response.text);
    } else {
        console.log("response error");
    }
}

我需要返回一些二进制文件以响应该请求。这是JSP代码

<%@ page import="java.io.FileInputStream" %>
<%@ page import="java.io.BufferedInputStream"  %>
<%@ page import="java.io.File"  %>
<%@ page import="java.io.IOException" %>

<%
    ServletOutputStream outStream=response.getOutputStream();
    File myfile = new File("/tmp/attachment.zip");
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition","attachment;filename=attachment.zip");
    response.setContentLength( (int) myfile.length( ) );
    FileInputStream input = new FileInputStream(myfile);
    BufferedInputStream buf = new BufferedInputStream(input);
    int readBytes = 0;
    while((readBytes = buf.read( )) != -1)
        outStream.write(readBytes);
    outStream.flush();
    outStream.close();
    buf.close();
%>

(“application / x-download”/“application / force-download”也使用FireFox和Chrome进行了测试)

我希望出现“保存文件”浏览器对话框。

我试过

document.write(response.text)

_rpcCallback 函数中,我可以看到相应的响应标头

HTTP/1.1 200 OK
Date: Fri, 03 May 2013 08:16:49 GMT
Expires: Thu, 01-Jan-1970 00:00:00 GMT
Content-Type: application/octet-stream
Content-Length: 20021
Set-Cookie: JSESSIONID=11ebfk145b34z;Path=/zimlet
Content-Disposition: attachment;filename=attachment.zip

以及二进制响应正文内容,但什么也没发生。

为了显示“下载文件”对话框而不是将文件打印为文本,必须包含哪些代码 _rpcCallback 功能?

使用Zimbra Desktop 7.2.2 GA进行测试

1 个答案:

答案 0 :(得分:0)

感谢Julian找到了解决方案,这太简单了:

window.open(fileUrl);