使用Axios从前端上传文件并且下载后端返回的文件
前端代码:
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()">×</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()">×</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()">×</a><strong>SUCCESS!</strong> JRXML file generated successfully!</div></div>
</body>
</html>
相关文章:
使用Axios从前端上传文件并且下载后端返回的文件
前端代码: 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({…...
open 函数到底做了什么
使用设备之前我们通常都需要调用 open 函数,这个函数一般用于设备专有数据的初始化,申请相关资源及进行设备的初始化等工作,对于简单的设备而言,open 函数可以不做具体的工作,你在应用层通过系统调用 open 打开设备…...
ue引擎游戏开发笔记(32)——为游戏添加新武器装备
1.需求分析: 游戏中角色不会只有一种武器,不同武器需要不同模型,甚至可能需要角色持握武器的不同位置,因此需要添加专门的武器类,方便武器后续更新,建立一个武器类。 2.操作实现: 1.在ue5中新建…...
【个人博客搭建】(17)使用FluentValidation 参数校验
FluentValidation 是一个用于 .NET 的开源验证库,它提供了一种流畅的接口和强类型验证规则,使得验证逻辑表达得更加清晰和简洁。(Apache-2.0) FluentValidation 的主要作用包括: 提高代码可读性:通过使用 F…...
数据结构===散列表
文章目录 概要散列思想散列函数散列冲突开放寻址法装载因子 链表法 代码Java小结 概要 散列表是一种很有趣的数据结构。 散列表是一个很有用的数据结构。它是数组演练而来的,又是一个基于数组的扩展的数据结构。接下来看看。 散列思想 散列表用的是数组支持按照下…...
10G MAC层设计系列-(2)MAC RX模块
一、概述 MAC RX模块的需要进行解码、对齐、CRC校验。 因为在空闲的时候10G PCS/PMA会一直向外吐空闲符(x07)所以需要根据开始符、结束符将有效数据从码流中截取,也就是解码。 因为开始字符的所在位置有两种形式,而结束字符的位…...
解码Starknet Verifier:深入逆向工程之旅
1. 引言 Sandstorm为: 能提交独立proof给StarkWare的Ethereum Verifier,的首个开源的STARK prover。 开源代码见: https://github.com/andrewmilson/sandstorm(Rust) L2Beat 提供了以太坊上Starknet的合约架构图&…...
【C++语言】类和对象--默认成员函数 (中)
文章目录 前言类的六个默认成员函数:1. 构造函数概念特性做了什么?易错注意:显式定义和默认构造函数 2. 析构函数概念特征做了什么?注意事项: 3.拷贝构造函数概念特征做了什么?注意事项: 4.赋值运算符重载…...
前端递归常见应用
概览 在 JavaScript 中,递归是一种编程技术,指的是函数直接或间接调用自身的过程。 递归通常用于解决可以分解为相同子问题的问题。通过不断地将问题分解成更小的、相似的子问题,直到达到某种基本情况(不再需要进一步递归的简单情…...
AI工具如何改变我们的工作与生活
AI工具在当今社会中扮演着越来越重要的角色,它们已经开始改变着我们的工作方式和生活方式。在接下来的2000字篇幅中,我将详细探讨AI工具如何影响我们的工作和生活。 AI工具在工作中的影响: 自动化和智能化生产流程: AI工具可以通…...
深入了解C/C++的内存区域划分
🔥个人主页:北辰水墨 🔥专栏:C学习仓 本节我们来讲解C/C的内存区域划分,文末会附加一道题目来检验成果(有参考答案) 一、大体有哪些区域?分别存放什么变量开辟的空间? …...
C++构造函数和析构函数的调用顺序
一般情况下,调用析构函数的次序正好与调用构造函数的次序相反,也就是最先被调用的构造函数,其对应的析构函数最后被调用,而最后被调用的构造函数,其对应的析构函数最先被调用。 当然对象的构造函数和析构函数调用时机和…...
智能家居1 -- 实现语音模块
项目整体框架: 监听线程4: 1. 语音监听线程:用于监听语音指令, 当有语音指令过来后, 通过消息队列的方式给消息处理线程发送指令 2. 网络监听线程:用于监听网络指令,当有网络指令过来后, 通过消息队列的方…...
Leetcode 3139. Minimum Cost to Equalize Array
Leetcode 3139. Minimum Cost to Equalize Array 1. 解题思路2. 代码实现 题目链接:3139. Minimum Cost to Equalize Array 1. 解题思路 这一题是一道hard的题目,而且看了一下答出率低的离谱,就一开始被吓到了,不过实际做了一下…...
【element-ui】el-table横向滚动后,通过is-scrolling-left获取滚动高度失效的问题
el-table横向滚动后,通过is-scrolling-left获取滚动高度失效的问题 需求 现在有一个需求,需要监听el-table的纵向滚动,当滚动高度达到特定值时进行一些操作。 代码如下: methods:{throttledHandleScroll() {// 如果已经有定时器…...
JAVA中的日期
获取当前的日期 LocalDate LocalDate today LocalDate.now();System.out.println("今天是:"today);//今天是:2024-05-06String format today.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));System.out.println("今天是:"…...
一起了解开源自定义表单的优势表现
随着社会的进步和科技的发展,越来越多的中小企业希望采用更为先进的软件平台,助力企业实现高效率的流程化管理。低代码技术平台、开源自定义表单已经慢慢走入大众视野,成为一款灵活、高效的数字化转型工具。流辰信息专注于低代码技术平台的研…...
体育老师工资高吗,奖金有吗
教师的薪资水平与多种因素相关,包括教育经验、工作地点、学校类型以及个人的教学成果等。在讨论体育教师的工资问题时,不能仅仅关注数字,更应了解教育价值和个人发展。 初中体育教师的工资水平受多种因素影响。根据网络统计的数据,…...
Linux驱动开发——(十一)INPUT子系统
目录 一、input子系统简介 二、input驱动API 2.1 input字符设备 2.2 input_dev结构体 2.3 上报输入事件 2.4 input_event结构体 三、代码 3.1 驱动代码 3.2 测试代码 四、平台测试 一、input子系统简介 input子系统是管理输入的子系统,和pinctrl、gpio子…...
大数据毕业设计Python+Django旅游景点评论数据采集分析可视化系统 NLP情感分析 LDA主题分析 bayes分类 旅游爬虫 旅游景点评论爬虫 机器学习 深度学习 人工智能 计算机毕业设计
毕业论文(设计)开题报告 学生姓名 学 号 所在学院 信息工程学院 专 业 指导教师姓名 指导教师职称 工程师 助教 指导教师单位 论文(设计)题目 基于朴素贝叶斯算法旅游景点线上评价情感分析 开 题 报 告…...
基于大模型的 UI 自动化系统
基于大模型的 UI 自动化系统 下面是一个完整的 Python 系统,利用大模型实现智能 UI 自动化,结合计算机视觉和自然语言处理技术,实现"看屏操作"的能力。 系统架构设计 #mermaid-svg-2gn2GRvh5WCP2ktF {font-family:"trebuchet ms",verdana,arial,sans-…...
Cesium1.95中高性能加载1500个点
一、基本方式: 图标使用.png比.svg性能要好 <template><div id"cesiumContainer"></div><div class"toolbar"><button id"resetButton">重新生成点</button><span id"countDisplay&qu…...
MMaDA: Multimodal Large Diffusion Language Models
CODE : https://github.com/Gen-Verse/MMaDA Abstract 我们介绍了一种新型的多模态扩散基础模型MMaDA,它被设计用于在文本推理、多模态理解和文本到图像生成等不同领域实现卓越的性能。该方法的特点是三个关键创新:(i) MMaDA采用统一的扩散架构…...
React19源码系列之 事件插件系统
事件类别 事件类型 定义 文档 Event Event 接口表示在 EventTarget 上出现的事件。 Event - Web API | MDN UIEvent UIEvent 接口表示简单的用户界面事件。 UIEvent - Web API | MDN KeyboardEvent KeyboardEvent 对象描述了用户与键盘的交互。 KeyboardEvent - Web…...
第 86 场周赛:矩阵中的幻方、钥匙和房间、将数组拆分成斐波那契序列、猜猜这个单词
Q1、[中等] 矩阵中的幻方 1、题目描述 3 x 3 的幻方是一个填充有 从 1 到 9 的不同数字的 3 x 3 矩阵,其中每行,每列以及两条对角线上的各数之和都相等。 给定一个由整数组成的row x col 的 grid,其中有多少个 3 3 的 “幻方” 子矩阵&am…...
Android Bitmap治理全解析:从加载优化到泄漏防控的全生命周期管理
引言 Bitmap(位图)是Android应用内存占用的“头号杀手”。一张1080P(1920x1080)的图片以ARGB_8888格式加载时,内存占用高达8MB(192010804字节)。据统计,超过60%的应用OOM崩溃与Bitm…...
Element Plus 表单(el-form)中关于正整数输入的校验规则
目录 1 单个正整数输入1.1 模板1.2 校验规则 2 两个正整数输入(联动)2.1 模板2.2 校验规则2.3 CSS 1 单个正整数输入 1.1 模板 <el-formref"formRef":model"formData":rules"formRules"label-width"150px"…...
代理篇12|深入理解 Vite中的Proxy接口代理配置
在前端开发中,常常会遇到 跨域请求接口 的情况。为了解决这个问题,Vite 和 Webpack 都提供了 proxy 代理功能,用于将本地开发请求转发到后端服务器。 什么是代理(proxy)? 代理是在开发过程中,前端项目通过开发服务器,将指定的请求“转发”到真实的后端服务器,从而绕…...
C++.OpenGL (14/64)多光源(Multiple Lights)
多光源(Multiple Lights) 多光源渲染技术概览 #mermaid-svg-3L5e5gGn76TNh7Lq {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-3L5e5gGn76TNh7Lq .error-icon{fill:#552222;}#mermaid-svg-3L5e5gGn76TNh7Lq .erro…...
Netty从入门到进阶(二)
二、Netty入门 1. 概述 1.1 Netty是什么 Netty is an asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients. Netty是一个异步的、基于事件驱动的网络应用框架,用于…...
