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

news/2024/5/19 11:43:40

前端代码:

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.mrgr.cn/p/66332612

相关文章

用龙梦迷你电脑福珑2.0做web服务器

用龙梦迷你电脑福珑2.0上做web服务器是可行的。已将一个网站源码放到该电脑&#xff0c;在局域网里可以访问网站网页。另外通过在同一局域网内的一台windows10电脑上安装花生壳软件&#xff0c;也可以在外网访问该内网服务器网站网页。该电脑的操作系统属于LAMP。在该电脑上安装…

【Linux网络编程】自定义协议+HTTP协议

【Linux网络编程】自定义协议HTTP协议 目录 【Linux网络编程】自定义协议HTTP协议协议定制&#xff0c;序列化和反序列化应用层中的HTTP认识URL&#xff08;网址&#xff09;urlencode和urldecodeHTTP协议格式使用telnet获取百度的根目录资源HTTP的方法表单 HTTP的状态码HTTP常…

工作感受月记(202405月)

2024年05月06号 新的一月工作天,旧事未清理,新事不停生。 今日工作事项: 1/ 来了一个新案例,apim stv1 升级到stv2的情况,客户需要noam同学来帮助建会议处理问题。 2/ 自己研究durable function的4001端口问题,证明确实是gRPC需要使用,用于 isolated process处理时候,进…

ROS 2边学边练(43)-- 利用GTest写一个基本测试(C++)

前言 在ROS&#xff08;Robot Operating System&#xff09;中&#xff0c;gtest&#xff08;Google Test&#xff09;是一个广泛使用的C测试框架&#xff0c;用于编写和执行单元测试。这些测试可以验证ROS节点、服务和消息等的正确性和性能。 如果我们需要在写的包中添加测试&…

RockChip Android13 NFC SL6320移植

环境:RK3568 Android13 一:驱动移植 1、驱动 将SL6320驱动代码拷贝至kernel-5.10/drivers/misc/sl6320/ 特殊说明:勿将驱动代码放置于kernel-5.10/drivers/nfc/目录下,会导致sl6320驱动生成设备节点时因/dev/nfc节点以创建而加载失败。 2、DTS 本次硬件设计电路走I2C协…

冲刺第三天

今天继续优化登录界面,寻找到了app的图标和想出了名字,

软件测试必问的33个面试题

1.你为什么选择软件测试行业 因为之前有了解软件测试这个行业&#xff0c;觉得他的发展前景很好。 2.根据你以前的工作经验描述一下软件开发、测试过程&#xff0c;由那些角色负责&#xff0c;你做什么 要有架构师、开发经理、测试经理、程序员、测试员。我在里面主要是负责所…

【MyBatis】深入解析MyBatis:高效操作数据库技术详解

&#x1f493; 博客主页&#xff1a;从零开始的-CodeNinja之路 ⏩ 收录文章&#xff1a;【MyBatis】深入解析MyBatis&#xff1a;高效操作数据库技术详解 &#x1f389;欢迎大家点赞&#x1f44d;评论&#x1f4dd;收藏⭐文章 目录 动态SQL1. \<if>标签2. \<trim&…

Spring 当中的Bean 作用域

Spring 当中的Bean 作用域 文章目录 Spring 当中的Bean 作用域每博一文案1. Spring6 当中的 Bean的作用域1.2 singleton 默认1.3 prototype1.4 Spring 中的 bean 标签当中scope 属性其他的值说明1.5 自定义作用域&#xff0c;一个线程一个 Bean 2. 总结:3. 最后&#xff1a; 每…

KaiwuDB 解析器之语义解析

KaiwuDB 解析器介绍 解析器是数据库系统的重要组成部分之一&#xff0c;主要的功能是将客户端输入的 SQL 语句分解为语法单元&#xff0c;然后将这些语法单元转化成数据库内部可识别的数据结构&#xff0c;最终生成数据库可以执行的计划。 KaiwuDB 的一条 SQL 执行的整个生命…

全国33个省228189个矿产地位置分布数据,含经纬度坐标/CSV格式

全国矿产地分布&#xff08;2021版&#xff09; 数据来源&#xff1a; 全国矿产地数据库2021版 (ngac.org.cn) http://data.ngac.org.cn/mineralresource/index.html 数据获取方法&#xff1a;树谷资料库大全&#xff08;2024年4月19日更新&#xff09; 进入网站后&#xf…

线程池核心原理浅析

由于系统资源是有限的,为了降低资源消耗,提高系统的性能和稳定性,引入了线程池对线程进行统一的管理和监控,本文将详细讲解线程池的使用、原理。前言 由于系统资源是有限的,为了降低资源消耗,提高系统的性能和稳定性,引入了线程池对线程进行统一的管理和监控,本文将详细…

04-19 周四 GitHub CI 方案设计

04-19 周四 GitHub CI 方案设计 时间版本修改人描述2024年4月19日14:44:23V0.1宋全恒新建文档2024年4月19日17:22:57V1.0宋全恒完成部署拓扑结构的绘制和文档撰写 简介 需求 由于团队最近把代码托管在GitHub上&#xff0c;为解决推理、应用的自动化CI的需要&#xff0c;调研了…

权益商城系统源码 现支持多种支付方式

简介:权益商城系统源码,支持多种支付方式,后台商品管理,订单管理,串货管理,分站管理,会员列表,分销日志,应用配置。 上传到服务器,修改数据库信息,导入数据库,即可账号密码:123456L 图片: 下载链接-点击

【onnxruntime】【GPU】windows10下onnxruntime-win-x64-gpu-1.15.0 C++版本源码编译教程

【onnxruntime】【GPU】windows10下onnxruntime-win-x64-gpu-1.15.0 C版本源码编译教程 提示:博主取舍了很多大佬的博文并亲测有效,分享笔记邀大家共同学习讨论 文章目录 【onnxruntime】【GPU】windows10下onnxruntime-win-x64-gpu-1.15.0 C版本源码编译教程前言准备工具cuda/…

Ubuntu22.04有线网络连接但是没网,网络图标显示问号

Ubuntu22.04有线网络连接但是没网&#xff0c;网络图标显示问号 问题描述解决方案 问题描述 有线网络连接 但是没网 且网络图标显示问号 解决方案 进入设置->隐私->在 连接情况 中关闭连接检查 关闭后 网络正常

基于Springboot的家具网站

基于SpringbootVue的家具网站设计与实现 开发语言&#xff1a;Java数据库&#xff1a;MySQL技术&#xff1a;SpringbootMybatis工具&#xff1a;IDEA、Maven、Navicat 系统展示 用户登录 首页 商家 家具信息 家居资讯 后台管理 后台首页 用户管理 商家管理 家具类型管理 家具…

ctf_web

ctfshow web13 访问题目链接一看是一道文件上传题,上传文件进行测试 上传php会显示 error suffix 因此推测会检测格式 当文件字数超出一定字数时,显示 error file zise 常规操作就是访问 .php.bak 、.phps 、.swp等文件,看看有没有源码泄露 这道题访问 upload.php.bak 成功获…

音频智能切换器JR-AR42-A

憬锐JR-AR42-A音频自动智能切换器(四切一)&#xff0c;具备四路模拟卡侬立体声音频输入&#xff0c;两路模拟卡侬立体声音频输出&#xff0c;其中输入第1路和输出第1路为断电直通通道。具有输入音频信号幅度判别&#xff0c;可设置门限电平和切换延时时间&#xff0c;可以根据需…

顺序表的实现

顺序表的实现/******************************************************************************************************** * * file name: Zqh_顺序表.c * author : keyword2024@163.com * date : 2024/05/05 * function : 顺序表的增删改查 * note : 模板 * * Copy…