当前位置: 首页 > news >正文

使用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()">&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>

相关文章:

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

前端代码&#xff1a; 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 函数&#xff0c;这个函数一般用于设备专有数据的初始化&#xff0c;申请相关资源及进行设备的初始化等工作&#xff0c;对于简单的设备而言&#xff0c;open 函数可以不做具体的工作&#xff0c;你在应用层通过系统调用 open 打开设备…...

ue引擎游戏开发笔记(32)——为游戏添加新武器装备

1.需求分析&#xff1a; 游戏中角色不会只有一种武器&#xff0c;不同武器需要不同模型&#xff0c;甚至可能需要角色持握武器的不同位置&#xff0c;因此需要添加专门的武器类&#xff0c;方便武器后续更新&#xff0c;建立一个武器类。 2.操作实现&#xff1a; 1.在ue5中新建…...

【个人博客搭建】(17)使用FluentValidation 参数校验

FluentValidation 是一个用于 .NET 的开源验证库&#xff0c;它提供了一种流畅的接口和强类型验证规则&#xff0c;使得验证逻辑表达得更加清晰和简洁。&#xff08;Apache-2.0&#xff09; FluentValidation 的主要作用包括&#xff1a; 提高代码可读性&#xff1a;通过使用 F…...

数据结构===散列表

文章目录 概要散列思想散列函数散列冲突开放寻址法装载因子 链表法 代码Java小结 概要 散列表是一种很有趣的数据结构。 散列表是一个很有用的数据结构。它是数组演练而来的&#xff0c;又是一个基于数组的扩展的数据结构。接下来看看。 散列思想 散列表用的是数组支持按照下…...

10G MAC层设计系列-(2)MAC RX模块

一、概述 MAC RX模块的需要进行解码、对齐、CRC校验。 因为在空闲的时候10G PCS/PMA会一直向外吐空闲符&#xff08;x07&#xff09;所以需要根据开始符、结束符将有效数据从码流中截取&#xff0c;也就是解码。 因为开始字符的所在位置有两种形式&#xff0c;而结束字符的位…...

解码Starknet Verifier:深入逆向工程之旅

1. 引言 Sandstorm为&#xff1a; 能提交独立proof给StarkWare的Ethereum Verifier&#xff0c;的首个开源的STARK prover。 开源代码见&#xff1a; https://github.com/andrewmilson/sandstorm&#xff08;Rust&#xff09; L2Beat 提供了以太坊上Starknet的合约架构图&…...

【C++语言】类和对象--默认成员函数 (中)

文章目录 前言类的六个默认成员函数&#xff1a;1. 构造函数概念特性做了什么&#xff1f;易错注意&#xff1a;显式定义和默认构造函数 2. 析构函数概念特征做了什么?注意事项&#xff1a; 3.拷贝构造函数概念特征做了什么&#xff1f;注意事项&#xff1a; 4.赋值运算符重载…...

前端递归常见应用

概览 在 JavaScript 中&#xff0c;递归是一种编程技术&#xff0c;指的是函数直接或间接调用自身的过程。 递归通常用于解决可以分解为相同子问题的问题。通过不断地将问题分解成更小的、相似的子问题&#xff0c;直到达到某种基本情况&#xff08;不再需要进一步递归的简单情…...

AI工具如何改变我们的工作与生活

AI工具在当今社会中扮演着越来越重要的角色&#xff0c;它们已经开始改变着我们的工作方式和生活方式。在接下来的2000字篇幅中&#xff0c;我将详细探讨AI工具如何影响我们的工作和生活。 AI工具在工作中的影响&#xff1a; 自动化和智能化生产流程&#xff1a; AI工具可以通…...

深入了解C/C++的内存区域划分

&#x1f525;个人主页&#xff1a;北辰水墨 &#x1f525;专栏&#xff1a;C学习仓 本节我们来讲解C/C的内存区域划分&#xff0c;文末会附加一道题目来检验成果&#xff08;有参考答案&#xff09; 一、大体有哪些区域&#xff1f;分别存放什么变量开辟的空间&#xff1f; …...

C++构造函数和析构函数的调用顺序

一般情况下&#xff0c;调用析构函数的次序正好与调用构造函数的次序相反&#xff0c;也就是最先被调用的构造函数&#xff0c;其对应的析构函数最后被调用&#xff0c;而最后被调用的构造函数&#xff0c;其对应的析构函数最先被调用。 当然对象的构造函数和析构函数调用时机和…...

智能家居1 -- 实现语音模块

项目整体框架: 监听线程4&#xff1a; 1. 语音监听线程:用于监听语音指令&#xff0c; 当有语音指令过来后&#xff0c; 通过消息队列的方式给消息处理线程发送指令 2. 网络监听线程&#xff1a;用于监听网络指令&#xff0c;当有网络指令过来后&#xff0c; 通过消息队列的方…...

Leetcode 3139. Minimum Cost to Equalize Array

Leetcode 3139. Minimum Cost to Equalize Array 1. 解题思路2. 代码实现 题目链接&#xff1a;3139. Minimum Cost to Equalize Array 1. 解题思路 这一题是一道hard的题目&#xff0c;而且看了一下答出率低的离谱&#xff0c;就一开始被吓到了&#xff0c;不过实际做了一下…...

【element-ui】el-table横向滚动后,通过is-scrolling-left获取滚动高度失效的问题

el-table横向滚动后&#xff0c;通过is-scrolling-left获取滚动高度失效的问题 需求 现在有一个需求&#xff0c;需要监听el-table的纵向滚动&#xff0c;当滚动高度达到特定值时进行一些操作。 代码如下&#xff1a; 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("今天是&#xff1a;"…...

一起了解开源自定义表单的优势表现

随着社会的进步和科技的发展&#xff0c;越来越多的中小企业希望采用更为先进的软件平台&#xff0c;助力企业实现高效率的流程化管理。低代码技术平台、开源自定义表单已经慢慢走入大众视野&#xff0c;成为一款灵活、高效的数字化转型工具。流辰信息专注于低代码技术平台的研…...

体育老师工资高吗,奖金有吗

教师的薪资水平与多种因素相关&#xff0c;包括教育经验、工作地点、学校类型以及个人的教学成果等。在讨论体育教师的工资问题时&#xff0c;不能仅仅关注数字&#xff0c;更应了解教育价值和个人发展。 初中体育教师的工资水平受多种因素影响。根据网络统计的数据&#xff0c…...

Linux驱动开发——(十一)INPUT子系统

目录 一、input子系统简介 二、input驱动API 2.1 input字符设备 2.2 input_dev结构体 2.3 上报输入事件 2.4 input_event结构体 三、代码 3.1 驱动代码 3.2 测试代码 四、平台测试 一、input子系统简介 input子系统是管理输入的子系统&#xff0c;和pinctrl、gpio子…...

大数据毕业设计Python+Django旅游景点评论数据采集分析可视化系统 NLP情感分析 LDA主题分析 bayes分类 旅游爬虫 旅游景点评论爬虫 机器学习 深度学习 人工智能 计算机毕业设计

毕业论文&#xff08;设计&#xff09;开题报告 学生姓名 学 号 所在学院 信息工程学院 专 业 指导教师姓名 指导教师职称 工程师 助教 指导教师单位 论文&#xff08;设计&#xff09;题目 基于朴素贝叶斯算法旅游景点线上评价情感分析 开 题 报 告…...

AI-调查研究-01-正念冥想有用吗?对健康的影响及科学指南

点一下关注吧&#xff01;&#xff01;&#xff01;非常感谢&#xff01;&#xff01;持续更新&#xff01;&#xff01;&#xff01; &#x1f680; AI篇持续更新中&#xff01;&#xff08;长期更新&#xff09; 目前2025年06月05日更新到&#xff1a; AI炼丹日志-28 - Aud…...

循环冗余码校验CRC码 算法步骤+详细实例计算

通信过程&#xff1a;&#xff08;白话解释&#xff09; 我们将原始待发送的消息称为 M M M&#xff0c;依据发送接收消息双方约定的生成多项式 G ( x ) G(x) G(x)&#xff08;意思就是 G &#xff08; x ) G&#xff08;x) G&#xff08;x) 是已知的&#xff09;&#xff0…...

visual studio 2022更改主题为深色

visual studio 2022更改主题为深色 点击visual studio 上方的 工具-> 选项 在选项窗口中&#xff0c;选择 环境 -> 常规 &#xff0c;将其中的颜色主题改成深色 点击确定&#xff0c;更改完成...

CMake 从 GitHub 下载第三方库并使用

有时我们希望直接使用 GitHub 上的开源库,而不想手动下载、编译和安装。 可以利用 CMake 提供的 FetchContent 模块来实现自动下载、构建和链接第三方库。 FetchContent 命令官方文档✅ 示例代码 我们将以 fmt 这个流行的格式化库为例,演示如何: 使用 FetchContent 从 GitH…...

Caliper 配置文件解析:config.yaml

Caliper 是一个区块链性能基准测试工具,用于评估不同区块链平台的性能。下面我将详细解释你提供的 fisco-bcos.json 文件结构,并说明它与 config.yaml 文件的关系。 fisco-bcos.json 文件解析 这个文件是针对 FISCO-BCOS 区块链网络的 Caliper 配置文件,主要包含以下几个部…...

docker 部署发现spring.profiles.active 问题

报错&#xff1a; org.springframework.boot.context.config.InvalidConfigDataPropertyException: Property spring.profiles.active imported from location class path resource [application-test.yml] is invalid in a profile specific resource [origin: class path re…...

服务器--宝塔命令

一、宝塔面板安装命令 ⚠️ 必须使用 root 用户 或 sudo 权限执行&#xff01; sudo su - 1. CentOS 系统&#xff1a; yum install -y wget && wget -O install.sh http://download.bt.cn/install/install_6.0.sh && sh install.sh2. Ubuntu / Debian 系统…...

JVM 内存结构 详解

内存结构 运行时数据区&#xff1a; Java虚拟机在运行Java程序过程中管理的内存区域。 程序计数器&#xff1a; ​ 线程私有&#xff0c;程序控制流的指示器&#xff0c;分支、循环、跳转、异常处理、线程恢复等基础功能都依赖这个计数器完成。 ​ 每个线程都有一个程序计数…...

Linux 中如何提取压缩文件 ?

Linux 是一种流行的开源操作系统&#xff0c;它提供了许多工具来管理、压缩和解压缩文件。压缩文件有助于节省存储空间&#xff0c;使数据传输更快。本指南将向您展示如何在 Linux 中提取不同类型的压缩文件。 1. Unpacking ZIP Files ZIP 文件是非常常见的&#xff0c;要在 …...

【LeetCode】算法详解#6 ---除自身以外数组的乘积

1.题目介绍 给定一个整数数组 nums&#xff0c;返回 数组 answer &#xff0c;其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。 题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。 请 不要使用除法&#xff0c;且在 O…...