springboot单文件下载和多文件压缩zip下载的实现

这篇文章主要介绍了springboot单文件下载和多文件压缩zip下载的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

文件下载

//下载单个文件 public void downloadFile(HttpServletResponse response){ String path = "D:testce1.txt" File file = new File(path); if(file.exists()){ String fileName = file.getName(); response.setHeader("Content-disposition", "attachment;fileName=" + fileName); download(response,file); } } public void download(HttpServletResponse response,File file){ FileInputStream fis = null; BufferedInputStream bis = null; OutputStream os = null; try { os = response.getoutputStream(); fis = new FileInputStream(file); bis = new BufferedInputStream(fis); byte[] buffer = new byte[bis.available()]; int i = bis.read(buffer); while(i != -1){ os.write(buffer, 0, i); i = bis.read(buffer); } } catch (Exception e) { e.printstacktrace(); } try { bis.close(); fis.close(); os.close(); } catch (IOException e) { e.printstacktrace(); } }

文件压缩下载

//多个文件,压缩成zip后下载 public void downloadMoreFile(HttpServletResponse response) { String test1= "D:testce1.txt"; String test2= "D:testce2.txt"; File tfile= new File(test1); File cfile= new File(test2); List files = new ArrayList(); files.add(tfile); files.add(cfile); if (tfile.exists() && cfile.exists()) { String zipTmp = "D:testce1.zip"; zipd(zipTmp,files,response); } } public void zipd(String zipTmp,List files,HttpServletResponse response){ File zipTmpFile = new File(zipTmp); try { if (zipTmpFile.exists()) { zipTmpFile.delete(); } zipTmpFile.createNewFile(); response.reset(); // 创建文件输出流 FileOutputStream fous = new FileOutputStream(zipTmpFile); ZipOutputStream zipOut = new ZipOutputStream(fous); zipFile(files, zipOut); zipOut.close(); fous.close(); downloadZip(zipTmpFile, response); } catch (IOException e) { e.printstacktrace(); } } //files打成压缩包 public void zipFile(List files, ZipOutputStream outputStream) { int size = files.size(); for (int i = 0; i

到此这篇关于springboot单文件下载和多文件压缩zip下载的实现的文章就介绍到这了,更多相关springboot文件压缩下载内容搜索编程之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程之家!

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...