使用spring框架ResponseEntity实现文件下载

目录

  • spring框架ResponseEntity实现文件下载
    • 后台代码
  • ResponseEntity免压缩多文件下载
    • 免压缩批量文件下载

spring框架ResponseEntity实现文件下载
后台代码
@RequestMapping("downLoad")public ResponseEntity downloadPromisePdf() {String fileName = "企业诚信守法承诺书.pdf"; try {byte[] pdf = **; //byte文件String dfileName = new String(fileName.getBytes("gb2312"), "iso8859-1"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", dfileName); return new ResponseEntity<>(pdf, headers, HttpStatus.OK); } catch (BuzEx e){logger.error( e.getMessage()); }catch (Exception e) {}return null; }

前端直接window.location.href='https://www.it610.com/downLoad';

ResponseEntity免压缩多文件下载
免压缩批量文件下载
后台ResponseEntity代码还是一次请求下载一个
前台js改为发出多个请求
js中先用数组储存需要下载的文件参数信息,然后循环数组执行下载方法,下载方法则先ajax判断文件是否存在,是则动态创建a标签批量下载文件
//获得文件数组ids后 循环下载方法$.each(ids,function(i,value){downLoad(fileFunctionPathArray[i],fileNameInServerArray[i],fileOriginalNameArray[i],ids[i]); })//下载方法function downLoad(fileFunctionPath,fileNameInServer,fileOriginalName,ids){$.ajax({//检查文件是否存在url: "/ResourceManage/resourceDownloaduserLink/checkPermission",data: {sysuserid: localStorage.getItem("id"),resourceid: ids},success: function (data) {//文件存在则创建动态a标签批量下载文件if (data.success) {//ResponseEntity下载文件的urlvar url = "../filehandle/downLoad.do?filePlatPath=" + "resource&fileFunctionPath=" + fileFunctionPath + "&fileNameInServer=" + fileNameInServer+ "&fileOriginalName=" + fileOriginalName; var fileName = fileNameInServer; downloadFile(url,fileName); //动态创建a标签 批量下载}}})}//动态创建a标签const downloadFile = (url, fileName = '') => {let eleLink = document.createElement('a'); eleLink.download = fileName; eleLink.style.display = 'none'; eleLink.href = https://www.it610.com/article/url; // 受浏览器安全策略的因素,动态创建的元素必须添加到浏览器后才能实施点击document.body.appendChild(eleLink); // 触发点击eleLink.click(); // 然后移除document.body.removeChild(eleLink); };

点击下载则会 批量同时下载
使用spring框架ResponseEntity实现文件下载
文章图片

【使用spring框架ResponseEntity实现文件下载】以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    推荐阅读