javascript下载文件几种方式,接收后台返回流下载或直接下载文件

news2024/10/7 8:22:21

目录

1 javascript下载文件7中方式

1.1 window.location.href下载

1.2 window.location下载

1.3 iframe下载

1.4 form表单的形式下载

1.5 a标签的方式下载

1.6 ajax方式后台返回文件流下载

1.7 axios方法后台返回流方式下载

 2.完整源码

1 javascript下载文件7中方式

1.1 window.location.href下载

/**
	*window.location.href下载
	*/
	function btn1() {
		debugger;
		window.location.href = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
	}

1.2 window.location下载

/**
	*window.location下载
	*/
	function btn2() {
		debugger;
		window.location='http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile';
	}

1.3 iframe下载

/***
	*iframe下载
	*/
	function btn3() {
		try {
			var elementIF = document.createElement("iframe");
			elementIF.src = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
			elementIF.style.display = "none";
			document.body.appendChild(elementIF);
		}catch(error) {
			console.log(error);
		}
	}

1.4 form表单的形式下载

/**
	*form表单的形式下载
	*/
	function btn4() {
		const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
		var form = $("<form>");
		form.attr("style", "display:none");
		/**target 属性规定一个名称或一个关键词,指示在何处打开 action URL,
		 * 即在何处显示提交表单后接收到的响应。
		 *
		 *_blank 在新窗口/选项卡中打开。
		 *_self 在同一框架中打开。(默认)
		 *_parent 在父框架中打开。
		 *_top 在整个窗口中打开。
		 *framename 在指定的 iframe 中打开。
		 */
		form.attr("target", "_self");
		form.attr("method", "get");
		form.attr("action", url);
		$("body").append(form);
		// 提交
		form.submit();
	}
	

1.5 a标签的方式下载

/**
	*a标签的方式下载
	**/
	function btn5() {
		const fileName = "Benjamin_Download_Test_File.pdf";
		const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
		var a = document.createElement("a");
		a.download = fileName;
		a.href = url;
		// 修复firefox中无法触发click
		$("body").append(a)
		a.click();
		$(a).remove();
	}

1.6 ajax方式后台返回文件流下载

/**
	*
	*ajax方式后台返回文件流下载、
	*success(data, textStatus, jqXHR):请求成功后的回调函数。参数:由服务器返回,并根据dataType参数进行处理后的数据;描述状态的字符串。还有 jqXHR(在jQuery 1.4.x的中,XMLHttpRequest) 对象 。在jQuery 1.5, 成功设置可以接受一个函数数组。每个函数将被依次调用。
	*
	*关键在于dataType和xhrFields的属性指定上,指定对属性才能返回blob文件流,dataType: 'binary',xhrFields: {responseType: 'blob'},
	*/
	function btn6() {
		debugger;
		const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
		$.ajax({
			url: url,
			type: 'get',
			data: {},
			contentType: 'application/json;charset=utf-8',
			// 指定服务器返回的类型,因为我们要返回文件流,所以类型为二进制数据
			dataType: 'binary',
			// 原生XMLHttpRequest 的属性,设置响应类型为blob,接收文件流
			xhrFields: {responseType: 'blob'},
			success: function(result, status, xhr) {
				const fileName = "Benjamin_Download_Test_File_20221225.pdf";
				// 可通过XMLHttpRequest对象,获取响应头
                console.log(xhr);
				// 浏览器兼容 参数Blob类型
                const downloadURL = (window.URL || window.webkitURL).createObjectURL(result);
				// 创建a标签
				var a = document.createElement('a');
				// 下载后文件的名字
				a.download = fileName;
				a.href = downloadURL;
				document.body.appendChild(a);
				a.click();
				
				setTimeout(function () {
                    // 移除内存中的临时文件路径和为下载而创建的a标签
                    URL.revokeObjectURL(downloadURL);
                    a.remove();
                }, 10000);
			
			},
			
			error: function (xhr, textStatus, errorMessage) {
                // 从响应头中获取异常信息,如果包含中文的话会乱码因此 后台URLEncoder.encode() + 前台decodeURIComponent() 防止乱码
                const errorInfo = decodeURIComponent(xhr.getResponseHeader("errorInfo"));
                // 对错误信息进行打印
                console.log(errorInfo);
            }
			
		});

	}

1.7 axios方法后台返回流方式下载

/**
	*axios方法后台返回流方式下载
	*/
	function btn7() {
		debugger;
		const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
		const fileName = "Benjamin_Download_Test_File_20221225.pdf";
		this.axios.get(url, {responseType: 'blob'}).then(response => {
			// 创建a标签
			let a = document.createElement("a");
			a.download = fileName;
			// 创建二进制对象
			const blob = new Blob([response.data]);
			const downloadURL = (window.URL || window.webkitURL).createObjectURL(blob);
			a.href = downloadURL;
			
			// 模拟点击
			a.click();
			
			//释放资源并删除创建的a标签
            URL.revokeObjectURL(downloadURL);// a.href
			document.body.removeChild(a);
		
		}).catch(error => { 
			console.log(error);
		});
	
	}

下载按钮: 

 都可以成功下载:

 2.完整源码

后台简单源码:

@RestController
@RequestMapping("/flower/beetl")
@CrossOrigin
public class BeetlController {

    @GetMapping(value = "/downloadFile")
    public void downloadFile(HttpServletResponse httpServletResponse) {
        File file = new File("C:\\Users\\admin\\Desktop\\download\\Benjamin_Download_Test_File.pdf");
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(file);
            os = httpServletResponse.getOutputStream();
            httpServletResponse.setContentType("application/octet-stream");
            httpServletResponse.setHeader("Content-Disposition", "attachment;fileName=Benjamin_Download_Test_File.pdf");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = is.read(bytes)) != -1) {
                os.write(bytes, 0, bytes.length);
                os.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

 html页面源码:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>7中下载方式</title>
</head>

<body>
	<div style="margin-left:60px;margin-top:20px">
		<button id="btn1" onclick="btn1()" style="background-color:red" >window.location.href下载</button><br> <br>
		<button id="btn2" onclick="btn2()" style="background-color:orange">window.location下载</button><br> <br>
		<button id="btn3" onclick="btn3()" style="background-color:yellow">iframe下载</button><br> <br>
		<button id="btn4" onclick="btn4()" style="background-color:green">form表单的形式下载</button><br> <br>
		<button id="btn5" onclick="btn5()" style="background-color:cyan">a标签的方式下载</button><br> <br>
		<button id="btn6" onclick="btn6()" style="background-color:blue">ajax方式后台返回文件流下载</button><br> <br>
		<button id="btn7" onclick="btn7()" style="background-color:purple">axios方法后台返回流方式下载</button><br> <br>
	</div>
    
</body>
<!-- <script th:src="@{js/jquery.min.js}"></script> -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


<script>
	
	/**
	*window.location.href下载
	*/
	function btn1() {
		debugger;
		window.location.href = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
	}
	
	/**
	*window.location下载
	*/
	function btn2() {
		debugger;
		window.location='http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile';
	}
	
	/***
	*iframe下载
	*/
	function btn3() {
		try {
			var elementIF = document.createElement("iframe");
			elementIF.src = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
			elementIF.style.display = "none";
			document.body.appendChild(elementIF);
		}catch(error) {
			console.log(error);
		}
	}
	
	/**
	*form表单的形式下载
	*/
	function btn4() {
		const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
		var form = $("<form>");
		form.attr("style", "display:none");
		/**target 属性规定一个名称或一个关键词,指示在何处打开 action URL,
		 * 即在何处显示提交表单后接收到的响应。
		 *
		 *_blank 在新窗口/选项卡中打开。
		 *_self 在同一框架中打开。(默认)
		 *_parent 在父框架中打开。
		 *_top 在整个窗口中打开。
		 *framename 在指定的 iframe 中打开。
		 */
		form.attr("target", "_self");
		form.attr("method", "get");
		form.attr("action", url);
		$("body").append(form);
		// 提交
		form.submit();
	}
	
	/**
	*a标签的方式下载
	**/
	function btn5() {
		const fileName = "Benjamin_Download_Test_File.pdf";
		const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
		var a = document.createElement("a");
		a.download = fileName;
		a.href = url;
		// 修复firefox中无法触发click
		$("body").append(a)
		a.click();
		$(a).remove();
	}
	
	/**
	*
	*ajax方式后台返回文件流下载、
	*success(data, textStatus, jqXHR):请求成功后的回调函数。参数:由服务器返回,并根据dataType参数进行处理后的数据;描述状态的字符串。还有 jqXHR(在jQuery 1.4.x的中,XMLHttpRequest) 对象 。在jQuery 1.5, 成功设置可以接受一个函数数组。每个函数将被依次调用。
	*
	*关键在于dataType和xhrFields的属性指定上,指定对属性才能返回blob文件流,dataType: 'binary',xhrFields: {responseType: 'blob'},
	*/
	function btn6() {
		debugger;
		const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
		$.ajax({
			url: url,
			type: 'get',
			data: {},
			contentType: 'application/json;charset=utf-8',
			// 指定服务器返回的类型,因为我们要返回文件流,所以类型为二进制数据
			dataType: 'binary',
			// 原生XMLHttpRequest 的属性,设置响应类型为blob,接收文件流
			xhrFields: {responseType: 'blob'},
			success: function(result, status, xhr) {
				const fileName = "Benjamin_Download_Test_File_20221225.pdf";
				// 可通过XMLHttpRequest对象,获取响应头
                console.log(xhr);
				// 浏览器兼容 参数Blob类型
                const downloadURL = (window.URL || window.webkitURL).createObjectURL(result);
				// 创建a标签
				var a = document.createElement('a');
				// 下载后文件的名字
				a.download = fileName;
				a.href = downloadURL;
				document.body.appendChild(a);
				a.click();
				
				setTimeout(function () {
                    // 移除内存中的临时文件路径和为下载而创建的a标签
                    URL.revokeObjectURL(downloadURL);
                    a.remove();
                }, 10000);
			
			},
			
			error: function (xhr, textStatus, errorMessage) {
                // 从响应头中获取异常信息,如果包含中文的话会乱码因此 后台URLEncoder.encode() + 前台decodeURIComponent() 防止乱码
                const errorInfo = decodeURIComponent(xhr.getResponseHeader("errorInfo"));
                // 对错误信息进行打印
                console.log(errorInfo);
            }
			
		});

	}
	
	/**
	*axios方法后台返回流方式下载
	*/
	function btn7() {
		debugger;
		const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
		const fileName = "Benjamin_Download_Test_File_20221225.pdf";
		this.axios.get(url, {responseType: 'blob'}).then(response => {
			// 创建a标签
			let a = document.createElement("a");
			a.download = fileName;
			// 创建二进制对象
			const blob = new Blob([response.data]);
			const downloadURL = (window.URL || window.webkitURL).createObjectURL(blob);
			a.href = downloadURL;
			
			// 模拟点击
			a.click();
			
			//释放资源并删除创建的a标签
            URL.revokeObjectURL(downloadURL);// a.href
			document.body.removeChild(a);
		
		}).catch(error => { 
			console.log(error);
		});
	
	}
	

</script>

<style>
	button{
		width:200px;
		height:35px;
	}

</style>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/114637.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Discrete Optimization课程笔记(4)—前沿与工具

目录 1.大规模邻域搜索(Large Neighborhood Search) Case1: 带时间窗的非对称TSP(Asymmetric TSP with Time Windows) 2.列生成算法(Column Generation) Case2: Cutting Stock 3.优化工具汇总 1.大规模邻域搜索(Large Neighborhood Search) 大规模邻域搜索是局部搜索和CP…

linux共享内存的使用

共享内存可以由多个程序同时访问的内存&#xff0c;能够避免进程间通信过程中的冗余数据拷贝&#xff0c;是IPC中最快的一种,特别适合用来作大块数据的传输。共享内存可以映射到不同的进程空间&#xff0c;这些进程间的数据传递就不再涉及内核。这个过程其实是把同一块物理内存…

Java高效率复习-Spring[Spring]

前言 Spring的学习还是很简单的&#xff0c;到SpringMVC的时候则会比较复杂了&#xff0c;因为要创建Web项目以及一些Web因素等等。 Spring的简介 Spring入门案例 导入依赖 <packaging>jar</packaging><dependencies><!-- 基于Maven依赖传递性&#x…

[ 代码审计篇 ] Fortify 安装及使用详解(一)Fortify 下载安装并设置语言为中文导出中文报告

&#x1f36c; 博主介绍 &#x1f468;‍&#x1f393; 博主介绍&#xff1a;大家好&#xff0c;我是 _PowerShell &#xff0c;很高兴认识大家~ ✨主攻领域&#xff1a;【渗透领域】【数据通信】 【通讯安全】 【web安全】【面试分析】 &#x1f389;点赞➕评论➕收藏 养成习…

毕业5年,我买房了

持续坚持原创输出&#xff0c;点击蓝字关注我吧 都说人到30就觉得时间过的很快&#xff0c;这句话确实不假&#xff0c;2022年我已经毕业五年&#xff0c;今年下半年也终于在成都高新区购房了&#xff0c;在这里有了自己的家。 购房对于大多数人来说肯定是人生一件大事吧&…

【Maven基础】单一架构案例(三)

第六节 业务功能&#xff1a;登录 1、显示首页 1.1、流程图 1.2、创建 PortalServlet 1.2.1、创建 Java 类 public class PortalServlet extends ViewBaseServlet {Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletExceptio…

NetSuite Decode函数

昨天是平安夜&#xff0c;小家伙仍然为圣诞老人的到来准备了礼物&#xff0c;这是他的传统。每年为了感谢圣诞老人和驯鹿的到来&#xff0c;他都会准备上点心、水果。今年&#xff0c;他认为驯鹿可能需要电力&#xff0c;所以准备了电池给它们享用。 真希望天真一直伴随他的成长…

nestjs学习

某种原因开始学习nestjs&#xff0c;想用nestjs做后端&#xff0c;mongodb做数据库来实现一个微信小程序的后台&#xff0c;开始了哼哧哼哧的爬代码之路。 如果想使用自己写的js或ts工具库&#xff0c;需要使用require进行导入&#xff01;&#xff01;否则找不到文件&#xff…

平衡二叉树的一系列操作:删除、插入(在二叉排序树中插入新结点后,如何保持平衡)、调整平衡等等等

平衡二叉树的插入&#xff08;在二叉排序树中插入新结点后&#xff0c;如何保持平衡&#xff09;1.平衡二叉树的定义2.平衡二叉树的插入&#xff08;调整最小不平衡子树A&#xff09;2.1LL&#xff08;在A的左孩子的左子树中插入导致不平衡&#xff09;2.2RR&#xff08;在A的右…

qt嵌入并运行外部exe

由于项目需要&#xff0c;要实现将一个外部exe运行在qt的窗口中。下面记录一下过程&#xff1a; 首先就是在qt中创建一个新项目 由于我这里没有用到画布&#xff0c;所以没有勾选Generate form 然后就会自动生成一个可运行的代码 然后将我下边的代码替换粘贴进去 #includ…

RabbitMQ 第二天 高级 7 RabbitMQ 高级特性 7.5 死信队列

RabbitMQ 【黑马程序员RabbitMQ全套教程&#xff0c;rabbitmq消息中间件到实战】 文章目录RabbitMQ第二天 高级7 RabbitMQ 高级特性7.5 死信队列7.5.1 死信队列概述7.5.2 代码实现7.5.3 小结第二天 高级 7 RabbitMQ 高级特性 7.5 死信队列 7.5.1 死信队列概述 死信队列&am…

[LeetCode周赛复盘] 第 325 场周赛20221225

[LeetCode周赛复盘] 第 325 场周赛20221225 一、本周周赛总结二、 [Easy] 6269. 到目标字符串的最短距离1. 题目描述2. 思路分析3. 代码实现三、[Medium] 6270. 每种字符至少取 K 个1. 题目描述2. 思路分析3. 代码实现四、[Medium] 6271. 礼盒的最大甜蜜度1. 题目描述2. 思路分…

<Linux线程同步>——《Linux》

目录 1. Linux线程同步 1.1条件变量 1.2同步概念与竞态条件 1.3条件变量函数 1.4 为什么pthread_ cond_ wait 需要互斥量? 1.5 条件变量使用规范 后记&#xff1a;●由于作者水平有限&#xff0c;文章难免存在谬误之处&#xff0c;敬请读者斧正&#xff0c;俚语成篇&am…

论文阅读技巧

文献阅读思维 为什么你花了大量的时间来看文献却没有收获&#xff1f;那是因为你漫无目的的看文献&#xff0c;能有什么收获&#xff1f;所以我们要带着两个问题有目的的阅读文献。这个目的是什么&#xff1f;就是为了给自己找创新思路。同时在看摘要的时候你问自己第一个问题…

Mac (M1)搭建QGC地面站环境

之前朋友介绍了一个活&#xff0c;刚开始以为是针对树莓派进行二次开发。到了之后才发现&#xff0c;全新的领域&#xff0c;抱着试一试的想法就蛮答应了下来。后来在搭建环境的过程了一路受挫&#xff0c;不过就在写此文前几分钟&#xff0c;终于看到了成功的标志&#xff0c;…

2022年春秋杯网络安全联赛-冬季赛RE部分题解

easy_python python字节码 逻辑整理后就给flag flag [204, 141, 44, 236, 111, 140, 140, 76, 44, 172, 7, 7, 39, 165, 70, 7, 39, 166, 165, 134, 134, 140, 204, 165, 7, 39, 230, 140, 165, 70, 44, 172, 102, 6, 140, 204, 230, 230, 76, 198, 38, 175] for i in rang…

C++进阶(一)C++新特性:智能指针、右值引用、lambda、多线程操作、function和bind、可变模板参数

layout: post title: C进阶&#xff08;一&#xff09;C新特性&#xff1a;智能指针、右值引用、lambda、多线程操作、function和bind、可变模板参数 description: C进阶&#xff08;一&#xff09;C新特性&#xff1a;智能指针、右值引用、lambda、多线程操作、function和bind…

圣诞节来啦,快把这个动态爱心送个那个TA

作者主页&#xff1a;Designer 小郑 作者简介&#xff1a;Java全栈软件工程师一枚&#xff0c;来自浙江宁波&#xff0c;负责开发管理公司OA项目&#xff0c;专注软件前后端开发&#xff08;Vue、SpringBoot和微信小程序&#xff09;、系统定制、远程技术指导。CSDN学院、蓝桥云…

_15LeetCode代码随想录算法训练营第十五天-C++二叉树

_15LeetCode代码随想录算法训练营第十五天-C二叉树 题目列表 110.平衡二叉树257.二叉树的所有路径404.左叶子之和 110.平衡二叉树 题目 给定一个二叉树&#xff0c;判断它是否是高度平衡的二叉树。 本题中&#xff0c;一棵高度平衡二叉树定义为&#xff1a; 一个二叉树每…

雪花算法和uuid比较

1. 雪花算法 ​ 现在的服务基本是分布式、微服务形式的&#xff0c;而且大数据量也导致分库分表的产生&#xff0c;对于水平分表就需要保证表中 id 的全局唯一性。对于 MySQL 而言&#xff0c;一个表中的主键 id 一般使用自增的方式&#xff0c;但是如果进行水平分表之后&…