使用Axios从前端上传文件并且下载后端返回的文件

devtools/2024/9/24 5:49:31/

前端代码:

function uploadAndDownload(){showLoading();const fileInput = document.querySelector('#uploadFile');const file = fileInput.files[0];const formData = new FormData()formData.append('file', file)return new Promise((resolve, reject) => {axios({url: '/generateJrxml',method: 'post',data: formData,responseType: 'blob',headers: {'Content-Type': 'multipart/form-data'}}).then(res => {const { data, headers } = resconst fileName = headers['content-disposition'].replace(/\w+;filename=(.*)/, '$1')const blob = new Blob([data], {type: headers['content-type']})let dom = document.createElement('a')let url = window.URL.createObjectURL(blob)dom.href = urldom.download = decodeURI(fileName)dom.style.display = 'none'document.body.appendChild(dom)dom.click()dom.parentNode.removeChild(dom)window.URL.revokeObjectURL(url)}).catch(e => {console.log(e)reject(e)})})}

后端代码 

    @PostMapping(value = "/generateJrxml", produces = "application/json")ResponseEntity<InputStreamResource> generateJrxmlFromExcel(@RequestParam("file") MultipartFile uploadFile){try {String fileContent = jasperJrxmlGenerateService.generateJrxmlFile(uploadFile)byte[] bytes = fileContent.getBytes("UTF-8")ByteArrayInputStream bais = new ByteArrayInputStream(bytes)HttpHeaders headers = new HttpHeaders()headers.add("Content-Disposition", "attachment;filename=" + uploadFile.getOriginalFilename().takeBefore('.') + ".jrxml")return ResponseEntity.ok().headers(headers).contentType(MediaType.parseMediaType("application/octet-stream")).body(new InputStreamResource(bais))}catch(Exception e){HttpHeaders headers = new HttpHeaders()return ResponseEntity.internalServerError().headers(headers)}}

完整的前端代码如下: 

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="stylesheet" href="jasper.css"><title>Jasper Helper</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"/>
<!--    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>-->
<!--    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>--><script src="https://unpkg.com/axios/dist/axios.min.js"></script><script type="text/javascript">function clickUpload(){document.getElementById("uploadFile").click();}function showFileName(files){const fileName = files[0].name;document.getElementById("file-name").innerHTML = fileName;}function showLoading(){var file = document.getElementById("uploadFile").value;if(file == ''){console.error("please upload file!");alertFileMissing();}else{document.querySelector('#load-icon').style.display = "inline-block";console.log('loading')}}function closeLoading(){document.querySelector('#load-icon').style.display = "none";console.log('end loading')}function closeAlert(){document.querySelector('#alert').style.display = "none";}function alertFileMissing(){document.querySelector('#alert').style.display = "inline-block";}function closeAlertSuccess(){document.querySelector('#alertSuccess').style.display = "none";}function alertSuccess(){document.querySelector('#alertSuccess').style.display = "inline-block";}function closeAlertFailure(){document.querySelector('#alertFailure').style.display = "none";}function alertFailure(){document.querySelector('#alertFailure').style.display = "inline-block";}function uploadAndDownload(){showLoading();const fileInput = document.querySelector('#uploadFile');const file = fileInput.files[0];const formData = new FormData()formData.append('file', file)return new Promise((resolve, reject) => {axios({url: '/generateJrxml',method: 'post',data: formData,responseType: 'blob',headers: {'Content-Type': 'multipart/form-data'}}).then(res => {closeLoading()const { data, headers } = resconst fileName = headers['content-disposition'].replace(/\w+;filename=(.*)/, '$1')const blob = new Blob([data], {type: headers['content-type']})let dom = document.createElement('a')let url = window.URL.createObjectURL(blob)dom.href = urldom.download = decodeURI(fileName)dom.style.display = 'none'document.body.appendChild(dom)dom.click()dom.parentNode.removeChild(dom)window.URL.revokeObjectURL(url)alertSuccess()}).catch(e => {closeLoading()console.log(e)alertFailure()reject(e)})})}</script>
</head>
<body class="jasper-wrap"><div class="container overflow-hidden text-center"><br/><br/><br/><br/><br/><br/><br/><br/><h3>Jasper Helper</h3><br/>
<!--        <form id="upload-form" action="/generateJrxml" method="post" enctype="multipart/form-data">--><form id="upload-form"><input type="file" id="uploadFile" name="file" accept=".xlsx,.xls" style="display:none;" onchange="showFileName(this.files)" required><button type="button" class="btn btn-outline-primary" onclick="clickUpload()"><svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" fill="currentColor" class="bi bi-file-earmark-arrow-up-fill" viewBox="0 0 16 16"><path d="M9.293 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4.707A1 1 0 0 0 13.707 4L10 .293A1 1 0 0 0 9.293 0M9.5 3.5v-2l3 3h-2a1 1 0 0 1-1-1M6.354 9.854a.5.5 0 0 1-.708-.708l2-2a.5.5 0 0 1 .708 0l2 2a.5.5 0 0 1-.708.708L8.5 8.707V12.5a.5.5 0 0 1-1 0V8.707z"/></svg>UPLOAD</button><br/><div id="file-name"></div><br/><button type="button" class="btn btn-success" onclick="uploadAndDownload()"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle" viewBox="0 0 16 16"><path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14m0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16"/><path d="m10.97 4.97-.02.022-3.473 4.425-2.093-2.094a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-1.071-1.05"/></svg>GENERATE</button></form><div class="container mt-3"><div class="spinner-border text-info" id="load-icon" style="display:none"></div></div><div id="alert" class="alert alert-warning" style="display:none"><a href="#" class="close" data-dismiss="alert" onclick="closeAlert()">&times;</a><strong>ERROR!</strong>Please upload file!</div><div id="alertFailure" class="alert alert-warning" style="display:none"><a href="#" class="close" data-dismiss="alert" onclick="closeAlertFailure()">&times;</a><strong>ERROR!</strong>Failed to generate JRXML file!</div><div id="alertSuccess" class="alert alert-success" style="display:none"><a href="#" class="close" data-dismiss="alert" onclick="closeAlertSuccess()">&times;</a><strong>SUCCESS!</strong> JRXML file generated successfully!</div></div>
</body>
</html>


http://www.ppmy.cn/devtools/31857.html

相关文章

cmd查看局域网内所有设备ip

说明&#xff1a;最近碰到一个新问题&#xff0c;就是有一个安卓设备&#xff0c;安装了一个app导致死机了&#xff0c;app设置了开机重启&#xff0c;所以&#xff0c;无论重启还是关机&#xff0c;都是进来就白屏&#xff0c; 这可把人愁坏了&#xff0c;直接死循环了 无论…

【Excel】excel计算相关性系数R、纳什效率系数NSE、Kling-Gupta系数KGE

对于采用的数据&#xff1a; B2:B10958是观测值的所在范围 C2:C10958是模型计算值的所在范围 一、相关系数R是用来衡量两个变量之间线性关系强度和方向的统计量。在水文学和气象学中&#xff0c;常用的相关系数是皮尔逊相关系数&#xff08;Pearson correlation coefficient&am…

前端初学者的 CSS 入门

文章导读&#xff1a;AI 辅助学习前端&#xff0c;包含入门、进阶、高级部分前端系列内容&#xff0c;当前是 CSS 的部分&#xff0c;瑶琴会持续更新&#xff0c;适合零基础的朋友&#xff0c;已有前端工作经验的可以不看&#xff0c;也可以当作基础知识回顾。 从这篇文章开始…

Golang 设计模式(行为型)

文章目录 策略模式迭代器模式访问者模式观察者模式命令模式模板方法模式责任链模式状态模式 策略模式 策略模式是一种行为型设计模式&#xff0c;它定义了一系列算法&#xff0c;并将每个算法封装成独立的对象&#xff0c;使得它们可以互相替换。在 Go 语言中&#xff0c;策略…

第十五届蓝桥杯省赛大学B组(c++)

很幸运拿了辽宁赛区的省一,进入6月1号的国赛啦... 这篇文章主要对第十五届省赛大学B组(C)进行一次完整的复盘,这次省赛2道填空题6道编程题: A.握手问题 把握手情景看成矩阵: 粉色部分是7个不能互相捂手的情况 由于每个人只能和其他人捂手, 所以黑色情况是不算的 1和2握手2和…

vue如何实现异步组件

在 Vue 中实现异步组件&#xff0c;通常是为了在需要时加载组件&#xff0c;从而优化应用的性能&#xff0c;特别是当组件很大或者只在某些特定条件下才需要时。Vue 提供了几种方式来定义和使用异步组件。 1. 使用 import() 语法 你可以使用 ES6 的 import() 语法来动态地导入…

【测试思考】高覆盖的测试用例不只要方法

昨天临睡前看到一篇博客文章&#xff0c;看起来是一位java后端写的【转测试/测试开发】的系列文章 我把他的一系列10多篇文章都看完了&#xff0c;个人觉得特别适合刚开始接触测试或者想对测试做一些了解的朋友。 其中&#xff0c;对于测试用例的设计&#xff0c;我之前有分享一…

leetcode_43.字符串相乘

43. 字符串相乘 题目描述&#xff1a;给定两个以字符串形式表示的非负整数 num1 和 num2&#xff0c;返回 num1 和 num2 的乘积&#xff0c;它们的乘积也表示为字符串形式。 注意&#xff1a;不能使用任何内置的 BigInteger 库或直接将输入转换为整数。 示例 1: 输入: num1 &q…