【问题标题】:Set content-type of response设置响应的内容类型
【发布时间】:2015-03-10 12:01:24
【问题描述】:

response的内容类型写完后能改吗?

我需要将响应写入 .txt 文件。如果有任何错误,它应该只返回 zip 文件而不是 .txt,以便让最终用户了解失败。

但即使我将内容类型设置为 zip 文件以防出现异常,它也不起作用。

【问题讨论】:

    标签: file servlets download zip content-type


    【解决方案1】:

    没有。您可以构建 zip(没有写入任何标题或任何响应),然后最后,如果成功,将 content-type 写入 zip 并将其打印到响应,如果没有,将 txt 写入 content-type并打印您的错误消息。

    伪代码:

    Zip zip = null;
    try
    {
      zip = buildZip();
    }
    catch(Exception ex)
    {
       response.setContentType("text/html");
       response.getOutputStream().print("Error");
       return;
    }
    response.setContentType("application/zip");
    response.setHeader("Content-disposition", "attachment; filename=zipfile.zip");
    zip.print(response.getOutputStream());
    

    【讨论】:

      猜你喜欢
      • 2019-03-03
      • 2012-04-20
      • 1970-01-01
      • 2010-12-12
      • 2021-05-23
      • 2016-12-05
      • 1970-01-01
      • 2011-03-12
      • 2021-04-20
      相关资源
      最近更新 更多