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

Pio*_*456 3 java struts file

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

response.setHeader("Content-Disposition", "attachment;filename=file.pdf");
Run Code Online (Sandbox Code Playgroud)

我想打开"保存/打开"框,但现在PDF内容在浏览器中写入:ex.

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

我在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;
Run Code Online (Sandbox Code Playgroud)

还缺少什么?

编辑

当我在Struts类中使用此代码时,它不起作用,但是当我在Servlet中使用此代码时,它正在工作.最奇怪的是,当我在action类中只将"response.sendRedirect()"写入Servlet(并且所有逻辑都在Servlet中)时,它也不起作用.

当我分析响应头时,这三个例子中的所有内容都是相同的.

Vin*_*lds 5

尝试将Content-Type标题更改为浏览器无法识别的内容.代替

response.setContentType("application/pdf");
Run Code Online (Sandbox Code Playgroud)

使用

response.setContentType("application/x-download");
Run Code Online (Sandbox Code Playgroud)

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

此外,验证在Content-Disposition标头中分号后是否存在单个空格对于触发所需行为也是有用的.因此,而不是以下行

response.setHeader("Content-Disposition", "attachment;filename=file.pdf");
Run Code Online (Sandbox Code Playgroud)

请改用以下内容.

response.setHeader("Content-Disposition", "attachment; filename=file.pdf");
Run Code Online (Sandbox Code Playgroud)