这篇文章给大家分享的是有关如何使用spring框架ResponseEntity实现文件下载的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

spring框架ResponseEntity实现文件下载后台代码

@RequestMapping("downLoad")publicResponseEntity<byte[]>downloadPromisePdf(){StringfileName="企业诚信守法承诺书.pdf";try{byte[]pdf=**;//byte文件StringdfileName=newString(fileName.getBytes("gb2312"),"iso8859-1");HttpHeadersheaders=newHttpHeaders();headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);headers.setContentDispositionFormData("attachment",dfileName);returnnewResponseEntity<>(pdf,headers,HttpStatus.OK);}catch(BuzExe){logger.error(e.getMessage());}catch(Exceptione){}returnnull;}

前端直接window.location.href='/downLoad';

ResponseEntity免压缩多文件下载免压缩批量文件下载

后台ResponseEntity代码还是一次请求下载一个

前台js改为发出多个请求

js中先用数组储存需要下载的文件参数信息,然后循环数组执行下载方法,下载方法则先ajax判断文件是否存在,是则动态创建a标签批量下载文件

//获得文件数组ids后循环下载方法$.each(ids,function(i,value){downLoad(fileFunctionPathArray[i],fileNameInServerArray[i],fileOriginalNameArray[i],ids[i]);})//下载方法functiondownLoad(fileFunctionPath,fileNameInServer,fileOriginalName,ids){$.ajax({//检查文件是否存在url:"/ResourceManage/resourceDownloaduserLink/checkPermission",data:{sysuserid:localStorage.getItem("id"),resourceid:ids},success:function(data){//文件存在则创建动态a标签批量下载文件if(data.success){//ResponseEntity下载文件的urlvarurl="../filehandle/downLoad.do?filePlatPath="+"resource&fileFunctionPath="+fileFunctionPath+"&fileNameInServer="+fileNameInServer+"&fileOriginalName="+fileOriginalName;varfileName=fileNameInServer;downloadFile(url,fileName);//动态创建a标签批量下载}}})}//动态创建a标签constdownloadFile=(url,fileName='')=>{leteleLink=document.createElement('a');eleLink.download=fileName;eleLink.style.display='none';eleLink.href=url;//受浏览器安全策略的因素,动态创建的元素必须添加到浏览器后才能实施点击document.body.appendChild(eleLink);//触发点击eleLink.click();//然后移除document.body.removeChild(eleLink);};

点击下载则会 批量同时下载

感谢各位的阅读!关于“如何使用spring框架ResponseEntity实现文件下载”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!