文件下载java实现代码
2018-07-20 来源:open-open
1. 通过FileInputStream读取文件输入流
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),读取文件类型
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(); } } }
标签: isp
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
上一篇:python简单爬虫
最新资讯
热门推荐