springboot单文件下载和多文件压缩zip下载的实现
单文件下载
//下载单个文件 publicvoiddownloadFile(HttpServletResponseresponse){ Stringpath="D:\test\ce\1.txt" Filefile=newFile(path); if(file.exists()){ StringfileName=file.getName(); response.setHeader("Content-Disposition","attachment;fileName="+fileName); download(response,file); } } publicvoiddownload(HttpServletResponseresponse,Filefile){ FileInputStreamfis=null; BufferedInputStreambis=null; OutputStreamos=null; try{ os=response.getOutputStream(); fis=newFileInputStream(file); bis=newBufferedInputStream(fis); byte[]buffer=newbyte[bis.available()]; inti=bis.read(buffer); while(i!=-1){ os.write(buffer,0,i); i=bis.read(buffer); } }catch(Exceptione){ e.printStackTrace(); } try{ bis.close(); fis.close(); os.close(); }catch(IOExceptione){ e.printStackTrace(); } }
多文件压缩下载
//多个文件,压缩成zip后下载 publicvoiddownloadMoreFile(HttpServletResponseresponse){ Stringtest1="D:\test\ce\1.txt"; Stringtest2="D:\test\ce\2.txt"; Filetfile=newFile(test1); Filecfile=newFile(test2); Listfiles=newArrayList<>(); files.add(tfile); files.add(cfile); if(tfile.exists()&&cfile.exists()){ StringzipTmp="D:\test\ce\1.zip"; zipd(zipTmp,files,response); } } publicvoidzipd(StringzipTmp,List files,HttpServletResponseresponse){ FilezipTmpFile=newFile(zipTmp); try{ if(zipTmpFile.exists()){ zipTmpFile.delete(); } zipTmpFile.createNewFile(); response.reset(); //创建文件输出流 FileOutputStreamfous=newFileOutputStream(zipTmpFile); ZipOutputStreamzipOut=newZipOutputStream(fous); zipFile(files,zipOut); zipOut.close(); fous.close(); downloadZip(zipTmpFile,response); }catch(IOExceptione){ e.printStackTrace(); } } //files打成压缩包 publicvoidzipFile(Listfiles,ZipOutputStreamoutputStream){ intsize=files.size(); for(inti=0;i 到此这篇关于springboot单文件下载和多文件压缩zip下载的实现的文章就介绍到这了,更多相关springboot文件压缩下载内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!