日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

java获取content-disposition_java – Content-Disposition附件不起作用 – 将...

發布時間:2025/4/17 54 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java获取content-disposition_java – Content-Disposition附件不起作用 – 将... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我正在嘗試在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中使用此代碼時,它正在工作.

最奇怪的是,當我在動作類中只將“response.sendRedirect()”寫入Servlet(并且所有邏輯都在Servlet中)時,它也不起作用.

當我分析響應頭時,這三個例子中的所有內容都是相同的.

總結

以上是生活随笔為你收集整理的java获取content-disposition_java – Content-Disposition附件不起作用 – 将...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。