• vue简单下载


    1.后台代码

     @PostMapping("/downloadList")
        public void downloadList(@RequestBody ApiRequestUtil<Map<String, Object>> request, HttpServletResponse response) throws Exception {
            //可有可无的校验
            ApiResponseCode errorCode = ParamsUtil.checkSecurity(request, md5Key, true);
            if (ApiResponseCode.SUCCESS == errorCode) {
                errorCode = sysUserService.authorityVerify(request.getData().get(ParamsConst.TOKEN).toString());
                if (errorCode != ApiResponseCode.SUCCESS) {
                    throw new Exception(String.valueOf(errorCode));
                }
                //获取数据
                String recruitId = ParamsUtil.getAndCheck(request.getData(), "recruitId", false);
                String doctorId = ParamsUtil.getAndCheck(request.getData(), "doctorId", false);
                String status = ParamsUtil.getAndCheck(request.getData(), "status", false);
                List<Map<String, Object>> replyList = rwsPatientCaseService.queryRecruitReplyList(recruitId, doctorId, status);
                //设置分页数据
                RwsPatientCaseHandler.download(replyList,response);
            } else {
                throw new Exception(String.valueOf(errorCode));
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    2.handler

    package com.fn.health.download.rwsPatientCase;
    
    import com.alibaba.excel.EasyExcel;
    import com.alibaba.excel.annotation.ExcelProperty;
    import com.fn.health.common.domain.DownloadResultDomain;
    import com.fn.health.common.utils.WebUtil;
    
    import javax.servlet.http.HttpServletResponse;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    import java.util.List;
    import java.util.Map;
    
    public class RwsPatientCaseHandler {
    
        public  static void download(List<Map<String, Object>> replyList, HttpServletResponse response){
            List<RwsPatientCaseExcel> excelList=RwsPatientCaseExcel.ToList(replyList);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            EasyExcel.write(out, RwsPatientCaseExcel.class).sheet("导出数据").doWrite(excelList);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(out.toByteArray());
            DownloadResultDomain downloadResultDomain = new DownloadResultDomain("患者数据.xlsx", byteArrayInputStream);
            WebUtil.downloadFile(response, downloadResultDomain);
        }
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    3. easyexcel文件

    package com.fn.health.download.rwsPatientCase;
    
    import cn.hutool.extra.spring.SpringUtil;
    import com.alibaba.excel.annotation.ExcelProperty;
    import com.fn.health.common.Constant;
    import com.fn.health.model.RwsGlobalVariable;
    import com.fn.health.service.RwsGlobalVariableService;
    import com.fn.health.service.RwsPatientCaseService;
    import lombok.Data;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Optional;
    
    @Data
    public class RwsPatientCaseExcel {
        @ExcelProperty(value = "推荐医生id")
        private String doctorId;
        @ExcelProperty(value = "病例姓名")
        private String patientName;
        @ExcelProperty(value = "病例征集id")
        private String recruitId;
        @ExcelProperty(value = "病例征集标题")
        private String recruitTitle;
        @ExcelProperty(value = "状态")
        private String statusText;
        @ExcelProperty(value = "创建时间")
        private String createTime;
    
        public static RwsPatientCaseExcel entityToExcel(Map<String, Object> rwsPatientCase,List<RwsGlobalVariable> rwsGlobalVariableList){
            Optional<RwsGlobalVariable> rwsGlobalVariableGet=rwsGlobalVariableList.stream().filter(x->x.getValue().equals(String.valueOf(rwsPatientCase.get("status")))).findFirst();
            if(rwsGlobalVariableGet.isPresent()){
                rwsPatientCase.put("statusText", rwsGlobalVariableGet.get().getText());
            }
            RwsPatientCaseExcel excel=new RwsPatientCaseExcel();
            excel.setDoctorId(String.valueOf(rwsPatientCase.get("doctorId")));
            excel.setPatientName(String.valueOf(rwsPatientCase.get("patientName")));
            excel.setRecruitId(String.valueOf(rwsPatientCase.get("recruitId")));
            excel.setRecruitTitle(String.valueOf(rwsPatientCase.get("recruitTitle")));
            excel.setStatusText(String.valueOf(rwsPatientCase.get("statusText")));
            excel.setCreateTime(String.valueOf(rwsPatientCase.get("createTime")));
            return excel;
        }
        public static List<RwsPatientCaseExcel> ToList(List<Map<String, Object>> mapList){
            RwsGlobalVariableService rwsGlobalVariableService= SpringUtil.getBean(RwsGlobalVariableService.class);
            List<RwsGlobalVariable> rwsGlobalVariableList=rwsGlobalVariableService.getGlobalVariable();
            List<RwsPatientCaseExcel> excelList=new ArrayList<>();
            for (Map<String, Object> entity: mapList) {
                RwsPatientCaseExcel excel=entityToExcel(entity,rwsGlobalVariableList);
                excelList.add(excel);
            }
            return excelList;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56

    4.开始搞前台,先写个配置文件

    这是之前一人写的,我加了一个download方法

    import request from "./request.js"
    function toQueryPair(key, value) {
    	if (typeof value == 'undefined'){
    		return key;
    	}
    	return key + '=' + encodeURIComponent(value === null ? '' : String(value));
    }
    function toQueryString(obj) {
    	var ret = [];
    	for(var key in obj){
    		key = encodeURIComponent(key);
    		var values = obj[key];
    		if(values && values.constructor == Array){//数组
    			var queryValues = [];
    			for (var i = 0, len = values.length, value; i < len; i++) {
    				value = values[i];
    				queryValues.push(toQueryPair(key, value));
    			}
    			ret = ret.concat(queryValues);
    		}else{ //字符串
    			ret.push(toQueryPair(key, values));
    		}
    	}
    	if(ret.length===0) return ''
    	return '?'+ret.join('&');
    }
    export default{
    	token:"",
    	width:'',
    	port:'',
    	login(url,data){
    		return request.login(request.url+url,data)
    	},
    	getdata(url,data,config={}){
    		config.headers = { token: this.token }
    		return request.getdata(request.url+url,data,config)
    	},
    	getdataToQuery(url,data,config={}){
    		config.headers = { token: this.token }
    		return request.getdata(request.url+url+toQueryString(data),{},config)
    	},
    	getdataForGet(url,data,config={}){
    		config.headers = { token: this.token }
    		return request.getdataForGet(request.url+url+toQueryString(data),config)
    	},
    	getimg(url){
    		return request.getimg(request.url1+url)
    	},
    	settoken(token){
    		this.token=token
    	},
    	setwidth(width){
    		this.width=width
    	},
    	setport(port){
    		this.port=port
    	},
    	getmap(url){
    		return axios.get(request.urlT+url).then(res=>{
    			return res
    		})
    	},
    	photodebug(url, data, config){
    		return axios.post(request.urlT+url, data, config).then(res=>{
    			return res
    		})
    	},
    
    	download(url,params){
    		return axios.post(request.url+url,params,{responseType:'blob'})
    	},
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72

    5.写个按钮

    			<div class="search2">
    				<el-button type="success" class="btn" @click="downloadList">下载el-button>
    			div>
    
    • 1
    • 2
    • 3

    6.点击事件

    downloadList(){
    				this.download(this.value=="请选择分类"?"1":this.value,this.recruitId==""?"1":this.recruitId,this.doctorId==""?"1":this.doctorId,-1)
    			},
    			download(value,recruitId,doctorId,index){
    				this.tableData=[]
    				this.list=[]
    				var data = {
    					"sign": 0,
    					"data": {
    						"pn": this.pageindex,
    						"ps": this.pagesize,
    						'token': this.common.token,
    						"timestamp": new Date().getTime()
    					}
    				}
    				if(value!=1){
    					data.data.status=value
    				}
    				if(recruitId!=1){
    					data.data.recruitId=recruitId
    				}
    				if(doctorId!=1){
    					data.data.doctorId=doctorId
    				}
    				var url="patientcase/downloadList"
    				this.common.download(url, data).then(res => {
    					const type = res.headers['content-type']
    					let BLOB = new Blob([res.data], { type: type });
    					let url = window.URL.createObjectURL(BLOB);
    					let link = document.createElement('a');
    					link.style.display = 'none';
    					link.href = url;
    					link.setAttribute('download', "患者.xlsx")
    					document.body.appendChild(link);
    					link.click();
    				})
    			},
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    7.总结

    这个是前端贴的原来一个人的代码,自己改了一点,没大改,还可以封装很多,比如download之后的返回,还有一些传参,都可以封装的,或者写的更优雅,附一段之前同事写的前端同步下载

          window.open(
            `/api/blade-system/taskUpload/downloadTemplate?${
              this.website.tokenHeader
            }=${getToken()}&businessType=data_agency_employee`
          );
    
    • 1
    • 2
    • 3
    • 4
    • 5

    有时间就封装封装,写的优雅些

  • 相关阅读:
    2023年CSP-J1入门级第一轮题解
    [LeetCode] 最后一个单词的长度【58】
    用户画像系列——推荐相关核心标签(偏好类)
    美国经典人工智能教材第3版出版!
    vue2-移动端创建
    SELinux,无semanage,Linux user到SELinux user的映射
    各种字符串Hash函数比较
    Oracle 11g升级19c 后部分查询功能很慢
    leetcode:面试题 17.04. 消失的数字(找单身狗/排序/公式)
    iptables与firewalld
  • 原文地址:https://blog.csdn.net/qq_39432715/article/details/133138103