java - Content-Disposition 附件不起作用 - 将位打印到屏幕

标签 java file struts

我正在尝试下载 Struts Action 类中的 PDF 文件。 问题是使用

response.setHeader("Content-Disposition", "attachment;filename=file.pdf");

我想打开“保存/打开”框,但现在 PDF 内容已写入浏览器: 例如。

%PDF-1.4 28 0 obj << /Type /XObject /Subtype /Image /Filter /DCTDecode /Length 7746 /Width 200 /Height 123 /BitsPerComponent 8 /ColorSpace /DeviceRGB >>...(cut)

我在 Chrome、Firefox 和 IE 下尝试这段代码(如下),在任何地方都一样。我也为此使用了不同的 PDF 文件。

我的代码片段:

try {
    URL fileUrl = new URL("file:///" + filePath);
    URLConnection connection = fileUrl.openConnection();
    inputStream = connection.getInputStream();
    int fileLength = connection.getContentLength();
    byte[] outputStreamBytes = new byte[100000];
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment;filename=file.pdf");
    response.setContentLength(fileLength);
    outputStream = response.getOutputStream();
    int iR;
    while ((iR = inputStream.read(outputStreamBytes)) > 0) {
        outputStream.write(outputStreamBytes, 0, iR);
    }

    return null;
} catch (MalformedURLException e) {
    logger.debug("service", "An error occured while creating URL object for url: "
        + filePath);
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return null;
} catch (IOException e) {
    logger.debug("service", "An error occured while opening connection for url: "
        + filePath);
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return null;
} finally {
    if (outputStream != null) {
        outputStream.close();
    }
    if (inputStream != null) {
        inputStream.close();
    }
    inputStream.close();
}
return null;

还缺什么吗?

编辑

当我在 Struts 类中使用这段代码时它不起作用,但是当我在 Servlet 中使用这段代码时它起作用了。 最奇怪的是,当我在操作类中只向 Servlet 写入“response.sendRedirect()”(并且所有逻辑都在 Servlet 中)时,它也不起作用。

当我分析响应 header 时,这三个示例中的所有内容都是相同的。

最佳答案

尝试将 Content-Type header 更改为浏览器无法识别的内容。而不是

response.setContentType("application/pdf");

使用

response.setContentType("application/x-download");

这将阻止浏览器对正文内容进行操作(包括插件对内容的处理),并强制浏览器显示“保存文件”对话框。

此外,验证是否有必要在 Content-Disposition header 中的分号后出现单个空格来触发所需的行为也可能很有用。因此,而不是下面一行

response.setHeader("Content-Disposition", "attachment;filename=file.pdf");

请改用以下内容。

response.setHeader("Content-Disposition", "attachment; filename=file.pdf");

关于java - Content-Disposition 附件不起作用 - 将位打印到屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6173454/

相关文章:

java - 自签名 Java Applet

python - 什么时候是使用 readline() 的好时机?

java - 尝试从扫描仪读取时文件内容被删除

java - 在java中改变语言

java - Java Queue 接口(interface)中的方法之间有什么区别?

java - XMLRootElement 在 Jersey 中将类转换为 XML

java - 在 Eclipse RCP 中显示 View 时传递参数

ios - 使用ASIHTTPRequest下载多个文件

javascript - 使用javascript在struts1中提交表单

java - 如何访问 Controller 上 Struts ActionForm 中的标签值