首页 > 编程知识 正文

springboot下载文件,springboot分段下载

时间:2023-05-03 20:50:50 阅读:127823 作者:180

1.ZipUtil工具类1.1请求者

import lombok.allargsconstructorimportlombok.noargsconstructorimportlombok.data/* @ author上的快笔* @ date 2021/08/2228 私有字符串文件名; } import java.io.*; import java.net.URL; import java.util.List; import java.util.zip.ZipEntry; import Java.util.zip.zip output stream; import javax.annotation.post construct; import javax.servlet.http.http servlet请求; import javax.servlet.http.http无servlet保罗; importorg.spring framework.beans.factory.annotation.auto wired; importorg.spring framework.stereotype.com ponent; /** * @author快笔* @ date 2021/08/27 * */@ componentpublicclassziputil { privatestatichttpservletresponse; @ autowiredprivatehttpservletresponseresponse 2; 隐私保护服务供应商; @ autowiredprivatehttpservletrequestrequest 2; @ postconstructpublicvoidbeforeinit ({ request=request 2; 响应=响应2; }/** *批量文件压缩下载* @param urlList批量下载文件链接到列表* @param zipName输出的压缩包名称*/publicstaticvoiddownzip (listfillist response.set content type (多部件/表单-数据); stringdownloadname=zip name '.zip '; //对于以客户端浏览器版本号、返回类型stringagent=request.get header (' user-agent ) )的try {//或IE为内核的浏览器: if (代理) 代理. contains ) (trident ) ) Downloadname=Java.net (else ) /处理非IE浏览器(downloadname=newstring ) download name . }catch(exceptione ) {e.printStackTrace ); } response.setheader (' content-disposition ',' attachment; fileName='' downloadName '' ' ); //设置压缩流:直接写入响应, try { zipos=newzipoutputstream (newbufferedoutputstream (response.get outstream ),用于在压缩的同时下载zip输出流zipos=null //设置压缩方法(catch(exceptione ) {e.printStackTrace ); //循环将文件写入压缩流数据输出流OS=null; for (filerequestrequest : urllist ) try ) file file=new file (request.get realurl ); //确定此处是否存在文件string filename=request.getfilename (); 添加//ZipEntry并向zipentry写入文件流zipos.putnextentry(newzipentry ) filename ); 操作系统=新数据输出流(zipos ); fileinputstreamis=new file inputstream (文件; byte[] b=new byte[1024]; int length=0; while((length=is.read ) b )!=-1 ) OS.write(b,0,length ); (}is.close ); zipos.closeEntry (; }catch(ioexceptione ) {e.printStackTrace ); () /关闭流try(OS.flush ) ); 操作系统. close (; zipos.close (; }catch(ioexceptione ) {e.printStackTrace ); }}2.服务层的实现代码如下,这里不粘贴控制器层和服务接口,所以很简单

@ overridepubliccommonresultzipdownload (requestbodylistfilerequestrequestlist )//演示,所以这里只做简单的异常判断,如果想做得更完美, 允许自定义系统异常(用于自定义具有相关gitee配置的全局系统异常的示例项目(if ) requestlist.size=0) returnnewcommonresult ) 4444 } stringzipname=newsimdateformat (' yyymmdd ).format (new date ) ); zip util.down zip (请求列表,请求. getdownloadname (); returnnewcommonresult(1111,“压缩包下载完成”); }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。