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

server/2024/9/24 12:18:07/

前端代码:

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/server/37339.html

相关文章

shell常用文件处理命令

1. 解压 1.1 tar 和 gz 文件 如果你有一个 .tar 文件,你可以使用以下命令来解压: tar -xvf your_file.tar在这个命令中,-x 表示解压缩,-v 表示详细输出(可选),-f 后面跟着要解压的文件名。 如果你的 .tar 文件同时被 gzip 压缩了(即 .tar.gz 文件),你可以使用以下…

我们该如何看待AIGC(人工智能)

引言 人工智能&#xff08;AI&#xff09;是当今世界科技发展的前沿领域之一&#xff0c;它正在以前所未有的速度和规模影响着我们的生活、工作和思考方式。AIGC&#xff0c;即人工智能生成内容&#xff08;Artificial Intelligence Generated Content&#xff09;&#xff0c…

【一刷《剑指Offer》】面试题 16:反转链表

力扣对应题目链接&#xff1a;206. 反转链表 - 力扣&#xff08;LeetCode&#xff09; 牛客对应题目链接&#xff1a;反转链表_牛客题霸_牛客网 (nowcoder.com) 核心考点 &#xff1a;链表操作&#xff0c;思维缜密程度。 一、《剑指 Offer》内容 二、分析题目 解题思路&#…

整理好了!2024年最常见 100 道 Java基础面试题(三十四)

上一篇地址&#xff1a;整理好了&#xff01;2024年最常见 100 道 Java基础面试题&#xff08;三十三&#xff09;-CSDN博客 六十七、内部类可以访问其外部类的成员吗&#xff1f; 内部类可以访问其外部类的成员&#xff0c;包括私有成员&#xff08;private members&#xf…

字节跳动后端或大数据基础知识面试题及参考答案(2万字长文)

目录 Redis的数据类型 Redis数据类型的底层数据结构 三次握手、四次挥手 Redis持久化机制

Golang中实现调用Windows API向指定目标发送ARP请求

简介 Go库中很多实现的arp都是支持osx/linux/bsd之类的&#xff0c; 但几乎没有支持windows的&#xff0c; 也试了一些方式&#xff0c; 目前还是选用调用windows的API&#xff0c; 记录一下这一次windows的API的调用经验。 实现 代码 package main/* #cgo CFLAGS: -I. #cgo …

基于FPGA的多路彩灯控制器VHDL代码Quartus仿真

名称&#xff1a;基于FPGA的多路彩灯控制器VHDL代码Quartus仿真&#xff08;文末获取&#xff09; 软件&#xff1a;Quartus 语言&#xff1a;VHDL 代码功能&#xff1a; 多路彩灯控制器 综合训练内容要求 设计一台基于FPGA的多路彩灯控制器的设计。要求如下 1.彩灯从左…

大数据技术原理与技术简答

1、HDFS中名称节点的启动过程 名称节点在启动时&#xff0c;会将FsImage 的内容加载到内存当中&#xff0c;此时fsimage是上上次关机时的状态。然后执行 EditLog 文件中的各项操作&#xff0c;使内存中的元数据保持最新。接着创建一个新的FsImage 文件和一个空的 Editlog 文件…