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

How to force browser to open "save as" dialog for binary response?

本文关键字:另存为 二进制 响应 对话框 何强制 浏览器      更新时间:2023-09-26

我正在开发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测试

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

window.open(fileUrl);