response下載檔案pdf
阿新 • • 發佈:2020-12-24
技術標籤:java7
public void getIdentificationBarFile(String formdataid, HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> searchParam = new HashMap<String, Object>();
searchParam.put("form_data_id", formdataid);
String pdfPath = null;
try {
pdfPath = taskinformationservice.getIdentificationBarFile(searchParam);
} catch (Exception e1) {
e1.printStackTrace();
}
if (pdfPath != null) {
File pdf = new File(pdfPath);
response.setContentType("text/html;charset=" + "UTF-8");
try (BufferedInputStream bis = new BufferedInputStream (new FileInputStream(pdfPath));
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());) {
//必寫,流必須關閉,java7中關閉流可以寫在try裡,就不用手動finally裡close了
response.setContentType("application/pdf");// 不同型別的檔案對應不同的MIME型別 // 重點突出
response.setHeader("Content-disposition" ,
"attachment; filename=" + new String("標識條.pdf".getBytes("UTF-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(pdf.length()));
//bis.available()返回緩衝區中要讀取的剩餘位元組數的總和
byte[] buffer = new byte[bis.available()];
bis.read(buffer);
bos.write(buffer);
} catch (Exception e) {
e.printStackTrace();
}
}
/*response.setContentType("text/html;charset=" + "UTF-8");
try {
Map<String, Object> searchParam = new HashMap<String, Object>();
searchParam.put("form_data_id", formdataid);
String pdfPath = taskinformationservice.getIdentificationBarFile(searchParam);
if(pdfPath!=null){
File pdf = new File(pdfPath);
response.setContentType("application/x-msdownload;");// 不同型別的檔案對應不同的MIME型別 // 重點突出
response.setHeader("Content-disposition","attachment; filename=" + new String("標識條.pdf".getBytes("UTF-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(pdf.length()));
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pdfPath));//這裡不是檔案pdf,而是檔案地址
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[2048];
int bytesRead;//獲得buffer的長度,沒有值返回-1
while (-1 != (bytesRead = bis.read(buffer, 0, buffer.length))) {
bos.write(buffer, 0, bytesRead);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//必寫,流必須關閉,java7中關閉流可以寫在try裡,就不用手動finally裡close了
if (bis != null)
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}*/
}