日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

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

我正在嘗試在Struts Action類中下載PDF文件.

問題是使用

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

我想打開“保存/打開”框,但現(xiàn)在PDF內(nèi)容在瀏覽器中寫入:

恩.

%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;

還缺少什么?

編輯

當(dāng)我在Struts類中使用此代碼時,它不起作用,但是當(dāng)我在Servlet中使用此代碼時,它正在工作.

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

當(dāng)我分析響應(yīng)頭時,這三個例子中的所有內(nèi)容都是相同的.

總結(jié)

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

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。