文件下载
最近学习文件下载,上网查阅了许多的资料。借鉴了一位大佬的经验。得出如下结果:
这是这位大佬博客地址:
http://blog.csdn.net/z69183787/article/details/38555913
接下来是代码实现
1.Controller 实现
/** * Created by 鸿鹄 on 2018/1/24. */ @RequestMapping("/fileDown") @RestController public class FileControllers { @Autowired urlConf urlConf; @Autowired MyZipCompressing zipFile; @RequestMapping("/ZipDown") public String FileDown( String name, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileName = UUID.randomUUID().toString() + ".zip"; String zipFileName="D:\\"+fileName; zipFile.zip(zipFileName, new File("D:\\myfile")); // 在服务器端创建打包下载的临时文件 this.downloadFile(new File(zipFileName),response,true); return null; } /** * 将压缩文件导入Response响应头中 * */ public void downloadFile(File file,HttpServletResponse response,boolean isDelete) { try { // 以流的形式下载文件。 BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath())); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("UTF-8"),"ISO-8859-1")); toClient.write(buffer); toClient.flush(); toClient.close(); if(isDelete) { file.delete(); //是否将生成的服务器端文件删除 } } catch (IOException ex) { ex.printStackTrace(); } } }
2.MyZipCompress工具类实现
/** * Created by 鸿鹄 on 2018/1/24. */ @Component public class MyZipCompressing { private int k = 1; // 定义递归次数变量 public MyZipCompressing() { // TODO Auto-generated constructor stub } /** * 压缩方法 * output 输出 * input 输入 * */ public void zip(String zipFileName, File inputFile) throws Exception { System.out.println("压缩中..."); //定义一个压缩流 ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); //缓存输出流 BufferedOutputStream bo = new BufferedOutputStream(out); //调用重载方法 zip(out, inputFile, inputFile.getName(), bo); bo.close(); out.close(); // 输出流关闭 System.out.println("压缩完成"); } /* *base 当前文件的文件夹名字 * */ public void zip(ZipOutputStream out, File f, String base,BufferedOutputStream bo) throws Exception { // 方法重载 //判断是否是目录 if (f.isDirectory()) { /*创建文件数组*/ File[] fl = f.listFiles(); System.out.println("fl.length="+fl.length); //如果是空文件将文件压入压缩中 if (fl.length == 0) { out.putNextEntry(new ZipEntry(base + "/")); // 创建zip压缩进入点base System.out.println(base + "/"); } //将文件逐个递归 for (int i = 0; i < fl.length; i++) { zip(out, fl[i], base + "/" + fl[i].getName(), bo); // 递归遍历子文件夹 } System.out.println("第" + k + "次递归"); k++; } else { //如果不是文件夹,直接打入压缩包 out.putNextEntry(new ZipEntry(base)); // 创建zip压缩进入点base System.out.println(base); //递归结束,将缓存buffer FileInputStream in = new FileInputStream(f); BufferedInputStream bi = new BufferedInputStream(in); int b; while ((b = bi.read()) != -1) { bo.write(b); // 将字节流写入当前zip目录 } bi.close(); in.close(); // 输入流关闭 } } }这是我吸取大佬精华的归纳和实现,贴上博客以备以后自己可以用。也希望能够帮助有需求的人解决问题!