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附件不起作用 – 将...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 泛型 get()_Java泛型
- 下一篇: 188tokens_Affiliate