😉 你好呀,我是爱编程的Sherry,很高兴在这里遇见你!我是一名拥有十多年开发经验的前端工程师。这一路走来,面对困难时也曾感到迷茫,凭借不懈的努力和坚持,重新找到了前进的方向。我的人生格言是——认准方向,坚持不懈,你终将迎来辉煌!欢迎关注我😁,我将在这里分享工作中积累的经验和心得,希望我的分享能够给你带来帮助。
文章目录
前言
在前端开发中,文件下载是一个常见的需求。根据不同的业务场景和浏览器兼容性要求,我们可以选择多种方法来实现这一功能。本文将介绍几种常用的前端文件下载技术,并附上简洁的代码示例。
方法概览
1、通过 <a>
标签进行简单下载
2、使用 fetch API
处理 Blob
文件下载
3、表单提交以支持复杂参数或 POST
请求
4、利用 iframe
进行无用户交互下载
5、借助 XMLHttpRequest
实现旧版浏览器兼容
6、结合 Blob
和FileSaver.js
简化操作
1. a标签下载
对于简单的文件下载,直接设置 <a>
标签的 href
属性并触发点击事件即可。这种方法依赖于服务器响应中的 Content-Disposition: attachment
头信息。
function downloadFile(url, filename, token) {
// 创建一个隐藏的 <a> 元素
const a = document.createElement('a');
a.style.display = 'none';
// 检查 URL 是否已经包含查询参数
const urlWithToken = url.includes('?')
? `${url}&token=${encodeURIComponent(token)}`
: `${url}?token=${encodeURIComponent(token)}`;
// 设置 <a> 元素的 href 属性为带有 token 的 URL
a.href = urlWithToken;
// 设置下载的文件名
a.download = filename || 'download';
// 将 <a> 元素添加到文档中
document.body.appendChild(a);
// 触发点击事件
a.click();
// 移除 <a> 元素
document.body.removeChild(a);
}
// 调用函数
downloadFile('https://example.com/path/to/file.pdf', 'file.pdf', 'yourTokenValue');
2. 使用 fetch API 下载 Blob 文件
当需要对下载过程有更多的控制时,比如处理二进制数据,可以使用 fetch
API 来获取文件内容,然后创建一个临时链接供用户下载。
function downloadFile(url, filename, token) {
fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
// 其他头部信息
}
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.blob();
})
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename || 'download';
a.style.display = 'none';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
})
.catch(error => {
console.error('Download failed:', error);
});
}
// 调用函数
downloadFile('https://example.com/path/to/file.pdf', 'file.pdf', 'yourTokenValue');
3. 表单提交下载
如果下载请求需要额外的数据或者必须是 POST 请求,则可以通过表单提交来实现。
<form id="downloadForm" action="https://example.com/download" method="POST" target="_blank">
<input type="hidden" name="token" value="yourTokenValue">
<!-- 其他需要的输入字段 -->
</form>
<script>
document.getElementById('downloadForm').submit();
</script>
4. 使用 iframe 触发下载
对于不需要用户交互的后台下载任务,可以使用隐藏的 iframe
元素。
<iframe id="downloadIframe" style="display:none;"></iframe>
<script>
function triggerDownload(url) {
const iframe = document.getElementById('downloadIframe');
iframe.src = url;
}
// 调用函数
triggerDownload('https://example.com/path/to/file.pdf');
</script>
5. 使用 XMLHttpRequest 下载
为了确保与旧版浏览器的兼容性,可以选择使用 XMLHttpRequest
来执行下载。
function downloadFile(url, filename, token) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader('Authorization', `Bearer ${token}`);
xhr.responseType = 'blob';
xhr.onload = function() {
if (this.status === 200) {
const blob = this.response;
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename || 'download';
a.style.display = 'none';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} else {
console.error('Download failed:', this.statusText);
}
};
xhr.onerror = function() {
console.error('Download failed:', this.statusText);
};
xhr.send();
}
// 调用函数
downloadFile('https://example.com/path/to/file.pdf', 'file.pdf', 'yourTokenValue');
6. FileSaver.js 库简化下载
引入第三方库 FileSaver.js
可以让文件下载更加简便,尤其是对于复杂的文件类型或较大的文件。
首先,安装 FileSaver.js
:
npm install file-saver
然后在代码中使用:
import { saveAs } from 'file-saver';
function downloadFile(url, filename, token) {
fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`, // 添加 token 到请求头
// 其他头部信息
}
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.blob();
})
.then(blob => {
saveAs(blob, filename || 'download');
})
.catch(error => {
console.error('Download failed:', error);
});
}
// 调用函数
downloadFile('https://example.com/path/to/file.pdf', 'file.pdf', 'yourTokenValue');
总结
每种方法都有其适用的场景和特点:
<a>
标签:适合简单的文件下载。
fetch
API:提供更灵活的文件处理方式。
表单提交:适合携带参数或发起 POST 请求。
iframe
:用于无用户交互的下载。
XMLHttpRequest
:保证旧版浏览器的支持。
FileSaver.js
:简化开发者的工作流程。
根据实际需求选择最合适的方法,可以提高用户体验并确保应用的健壮性。