【问题标题】:How to send a file from a servlet the "right" way?如何以“正确”的方式从 servlet 发送文件?
【发布时间】:2011-04-27 14:37:33
【问题描述】:

我正在尝试从 http servlet 向用户发送文件。 servlet 运行一些识别测试(根据请求),然后向客户端发送一个文件。

这通常有效,但现在我打开了我的 TOMCAT 服务器重定向到 https,当我尝试访问 servlet 并从 IE6 或 IE8 下载文件时,它失败了,我得到了这个异常:

java.lang.IllegalStateException: Cannot forward after response has been committed

(在 localhost.log 上)

ClientAbortException:  java.net.SocketException: Connection reset by peer: socket write error

(在 servlet 日志中)

发送的代码(简体):

private void sendFile(HttpServletResponse response, byte[] file, String clientFileName)
{
    ServletOutputStream op = null;

    setContentType(response);
    response.setHeader("Content-Disposition", "attachment; filename=\"" + clientFileName + "\"");
    // send byte array to output buffer. 
    op = response.getOutputStream();

    // Content Length must be set after all processing done.
    response.setContentLength((int) file.length);   
    op.write(file);
}

这是从 servlet 发送文件的正确方法吗?最好的方法是什么?

谢谢!!

更新

在此链接中使用了来自@BalusC 文章的代码: http://balusc.blogspot.com/2007/07/fileservlet.html

这使它起作用了。

从 Gmail 中使用时仍然无法在 IE6-IE8 中工作,因为 gmail 在这些浏览器中添加了一个过滤阶段。

更新 2

问题似乎出在 Gmail + Internet Explorer 6-8 上。 我假设 gmail 正在执行重定向(如果您在单击邮件中的链接后查看页面上的 url,这实际上非常明显)。 Client-Pull 技术是我唯一的解决方案吗?

【问题讨论】:

    标签: http file servlets file-io


    【解决方案1】:

    解决问题的方法是“客户端拉动”技术。 通过在标题中添加Refresh 值,我们可以让浏览器请求文件。

    这是我能想出的唯一解决方案,它克服了 gmail 在按下电子邮件中的链接时会使用重定向这一事实。

    在代码中我这样做了:

    response.setHeader("Refresh", "3; URL=\"" + url.toString() + "\"");
    forwardToJSP(request, response, "waitForBrowserRefreshPage.jsp");
    

    含义 - 3 秒后询问用户指定的 url,然后将文件传递给客户端。 forwardToJSP 方法显示“您将很快被转发,如果失败,请在此处提供链接”消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-14
      • 1970-01-01
      相关资源
      最近更新 更多