下载文件的三种具体实现方式
最编程
2024-06-27 07:14:57
...
一,window.open()
1.可以使用window.open()
直接完成文件的下载
二,使用a
标签的download
属性
1.代码
var link = document.createElement("a");
link.download ='xxx' //下载文件名称
link.href ='xxx' // 下载地址
link.style.display ="none"
link.click()
2.当请求返回的是二进制文件blob
时,也可以使用a
标志的方式下载文件。
let blob = new Blob([data],{type:''})
let link = document.createElement('a')[;
link.download = 'fileName';
link.href = URL.createObjectURL(blob); //生成指向blob文件的地址:blob:http://xxx
link.click()
三,使用form
表单下载文件
const post = (url, params) => {
// 创建form元素
var temp_form = document.createElement("form");
// 设置form属性
temp_form.action = url;
temp_form.target = "_self";
temp_form.method = "post";
temp_form.style.display = "none";
// 处理需要传递的参数
for (var x in params) {
var opt = document.createElement("textarea");
opt.name = x;
opt.value = params[x];
temp_form.appendChild(opt);
}
document.body.appendChild(temp_form);
// 提交表单
temp_form.submit();
}
四,注意事项
1.使用a
标签,和form
表单实测下来不能同时完成多个文件的下载,例如直接用一个for
循环来下载多个文件。有两种方法可以解决
(1)使用定时器间隔开来,不要让文件同时下载,实测可行
for (let i = 0; i < activeItems.length; i++) {
setTimeout(() => {
let a = document.createElement("a");
a.href = activeItems[i].downloadUrl;
a.download = "111";
a.click();
}, 1000 * i); //每个文件隔1s下载
}
(2)更可靠的方法是使用fetch
将文件转为blob
下载
function downloadIamge(imgSrc: string, fileName: string) {
let imgUrl = imgSrc;
let a = document.createElement("a");
fetch(imgUrl)
.then((res) => res.blob())
.then((blob) => {
a.href = URL.createObjectURL(blob);
a.download = fileName;
a.style.display = "none";
a.click();
window.URL.revokeObjectURL(a.href);
});
}
for (let i = 0; i < activeItems.length; i++) {
downloadIamge(activeItems[i].downloadUrl, activeItems[i].resourceId);
}
2,第一和第二种方式都是通过url
上传递参数,在长度上有限制,所以能传递的参数有限。而form
表单的文件下载方式没有参数的限制。
上一篇: 在前端下载文件的几种方法
下一篇: 网络前端以多种常见方式下载文件
推荐阅读
-
实现纯前端下载PDF链接文件的解决方案,不进行预览操作
-
三种实用的 HTML 锚点实现方式
-
三种实用的HTML锚点实现方式
-
实现在Java中进行文件(包括视频)下载,同时注意保持视频播放的流畅度与快进功能
-
四种实现 Lock 接口获取锁的方式:lock、tryLock、lockInterruptibly 的具体实践示例
-
四种实现 Lock 接口获取锁的方式:lock、tryLock、lockInterruptibly 的具体实践示例
-
实战攻略:工作流引擎深度解析 - 思维导图与具体案例" 目录概览: 1. 业务场景实战合集 2. 背景介绍:处理复杂场景 - 如请假、离职流程中的多步骤审批差异 - 详细示例:请假与离职流程的应用演示 3. 案例应用实例: - 内部企业系统(如OA)中的请假、离职流程审批 - 在内容创作工具(如PPT、海报模板)提供下载功能时,针对不同租户设置个性化审批流程 4. 技术选型与实践探讨 注:图片文件名 - "思维导图.png" 和 "请假流程.png" 无需修改。
-
理解工作流:自动化业务流程管理与Activiti实践" **简述** 工作流(Workflow)是一种利用电脑技术自动化管理业务流程的方式,让不同参与者按既定路径执行任务,确保文档、信息或任务在预设规则下顺利传递,最终达成期望的业务目标。 **核心概念** - **工作流自动化**: 计算机驱动业务流程处理与执行,如在参与者间自动传递文档和任务。 - **目标与应用**: 管理工作流程确保按时、由合适的人执行,同时允许人工介入以增强灵活性。 - **工作流框架示例**: Activiti、JBPM、OSWorkflow 和 Workflow,它们背后通常依赖数据库支持。 - **关键组件**: ProcessEngine 在 Activiti 中扮演核心角色,负责流程实例创建、数据管理和流程监控。 **相关领域** - **业务流程管理 (BPM)**: 一种系统性方法论,聚焦于构建并优化端到端卓越业务流程以提升企业业绩,在EMBA、MBA等商业课程中得到关注。 - **业务流程建模与标记语言 (BPMN)**: 用于绘制业务流程图的工具,探讨其在不同场景下的应用精确度、标准化价值以及未来发展愿景。 **辅助术语** - 流对象 (Flow Objects): BPMN 中用于描述流程中活动、决策、序列和其他元素的具体实现单元。
-
在HTML和JS中实现点击操作的三种方式
-
在HTML中轻松运用JavaScript:外链与内联方法总结 - 我们的建议:优先选择外部文件导入方式来实现JS脚本