一、概述
导出通过body传值,若依通过params传值,不满足需要,魔改一波。
二、看代码
1、js路径
src/utils/request.js
2、增加函数
// 通用下载方法 export function downloadByBody(url, params, filename, config) {downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })return service.post(url, params, {headers: { 'Content-Type': 'application/x-www-form-urlencoded' },responseType: 'blob',...config}).then(async (data) => {console.log(164, data.type, resText, rspObj)if (data.type === 'application/json') {const resText = await data.text();const rspObj = JSON.parse(resText);const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']Message.error(errMsg);} else {const blob = new Blob([data])saveAs(blob, filename)}downloadLoadingInstance.close();}).catch((r) => {console.error(r)Message.error('下载文件出现错误,请联系管理员!')downloadLoadingInstance.close();}) }
3、vue页面调用
import { downloadByBody } from '@/utils/request'
downloadByBody(url, body, `下载信息_${this.getDateStr()}.zip`)
4、Java接收参数
@PostMapping("/app/v2/export")public void exportUserV2(@RequestBody ExportUserParam exportUserParam, HttpServletRequest request, HttpServletResponse response) {}
5、Java导出
/*** 下载文件* @param fileName 文件名,无路径* @param path* @param response*/public static void download(String fileName, Path path, HttpServletResponse response) {try {log.info("文件下载,fileName:{}", fileName);response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);// 下载后文件中的汉字变成下划线(_)的问题解决String name = new String(fileName.getBytes("utf-8"), "iso-8859-1");response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + name + "\"");Files.copy(path, response.getOutputStream());} catch (Exception e) {throw BizException.error("文件下载失败");}}/*** 下载文件* @param file* @param response*/public static void download(File file, HttpServletResponse response) {try {Path filePath = Paths.get(file.getAbsolutePath()).toAbsolutePath().normalize();download(file.getName(), filePath, response);} catch (Exception e) {throw BizException.error("文件下载失败");}}
~~