js 实现下载文件
使用 Blob 和 URL.createObjectURL
通过创建 Blob 对象生成文件内容,结合 URL.createObjectURL 生成临时链接,触发下载:
function downloadFile(content, fileName, mimeType) {
const blob = new Blob([content], { type: mimeType });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, 100);
}
// 示例:下载文本文件
downloadFile('Hello World', 'example.txt', 'text/plain');
使用 fetch 下载远程文件
通过 fetch API 获取远程文件资源后转换为 Blob 下载:
async function downloadRemoteFile(url, fileName) {
const response = await fetch(url);
const blob = await response.blob();
const objectUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = objectUrl;
a.download = fileName || new URL(url).pathname.split('/').pop();
document.body.appendChild(a);
a.click();
setTimeout(() => {
URL.revokeObjectURL(objectUrl);
document.body.removeChild(a);
}, 100);
}
// 示例:下载远程图片
downloadRemoteFile('https://example.com/image.png', 'downloaded.png');
直接使用 Base64 数据
适用于已知 Base64 编码数据的场景:
function downloadBase64(base64Data, fileName, mimeType) {
const byteCharacters = atob(base64Data);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], { type: mimeType });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
a.click();
setTimeout(() => {
URL.revokeObjectURL(url);
}, 100);
}
兼容 IE 的替代方案
针对旧版 IE 浏览器使用 navigator.msSaveBlob:
function ieDownload(content, fileName, mimeType) {
if (window.navigator.msSaveBlob) {
// IE 10+
navigator.msSaveBlob(new Blob([content], { type: mimeType }), fileName);
} else {
const blob = new Blob([content], { type: mimeType });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
}
注意事项
- 跨域限制:远程文件下载需服务器配置 CORS 头
- 内存管理:及时调用
URL.revokeObjectURL释放内存 - 文件大小:Blob 方式适合中小文件,大文件建议服务端直接返回下载响应
- 移动端兼容性:部分移动浏览器可能限制程序化下载行为







