Java输出流文件下载
1 public void download(HttpServletResponse response){ 2 //读取一个classpath路径下的一个预下载文件 3 org.springframework.core.io.Resource res = new ClassPathResource(TEMPLATE_FILE_PATH); 4 InputStream ins = null; 5 OutputStream out = null; 6 try { 7 //设置response header 8 response.setCharacterEncoding("UTF-8"); 9 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 10 response.setHeader("Content-Disposition", "attachment;filename=template.xlsx"); 11 ins = new BufferedInputStream(res.getInputStream()); 12 out = new BufferedOutputStream(response.getOutputStream()); 13 //缓冲下载 14 byte[] buffer = new byte[BUFFER_SIZE]; 15 int n = 0; 16 while((n = ins.read(buffer)) != -1){ 17 out.write(buffer, 0, n); 18 } 19 } catch (IOException e) { 20 e.printStackTrace(); 21 }finally{ 22 //关闭流 23 IOUtils.closeQuietly(ins); 24 IOUtils.closeQuietly(out); 25 } 26 }
做个记录~