1. 經過FileInputStream讀取文件輸入流
java
public void export(String excelPath, String fileName) throws Exception{ //將文件存到指定位置 //讀取目標文件流,轉換調用下載 File resultFile = new File(excelPath); FileInputStream resultFileFi = new FileInputStream(resultFile); long l = resultFile.length(); int k = 0; byte abyte0[] = new byte[65000]; // 調用下載 response.setContentType("application/x-msdownload"); response.setContentLength((int) l); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); while ((long) k < l) { int j; j = resultFileFi.read(abyte0, 0, 65000); k += j; response.getOutputStream().write(abyte0, 0, j); } resultFileFi.close(); //轉換成功後,刪除臨時文件 resultFile.delete(); }
2. 注意getServletContext().getMimeType(fileName),讀取文件類型
app
public void export1(String excelPath, String fileName){ if (request.getParameter("file") != null) { fileName = request.getParameter("file"); } System.out.println(ServletActionContext.getServletContext().getMimeType(fileName)); response.setContentType(ServletActionContext.getServletContext().getMimeType(fileName)); response.setHeader("Content-disposition","attachment; filename="+fileName); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream( new FileInputStream(excelPath) ); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff,0,bytesRead); } } catch(final IOException e) { System.out.println ( "出現IOException." + e ); } finally { if (bis != null) try { bis.close(); } catch (IOException e) { e.printStackTrace(); } if (bos != null) try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } }