js实现点击下载功能
使用 <a> 标签实现下载
通过动态创建 <a> 标签并设置 download 属性实现文件下载。适用于已知文件 URL 或 Blob 数据:
function downloadFile(url, filename) {
const a = document.createElement('a');
a.href = url;
a.download = filename || 'downloaded-file';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
使用 Blob 对象下载动态内容
将字符串或二进制数据转换为 Blob 对象生成下载链接,适合动态生成内容的场景:
function downloadTextAsFile(text, filename) {
const blob = new Blob([text], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
downloadFile(url, filename);
setTimeout(() => URL.revokeObjectURL(url), 100);
}
处理跨域资源下载
当下载跨域资源时,需要先通过 fetch API 获取数据再转换为 Blob:
async function downloadCrossOriginFile(url, filename) {
const response = await fetch(url);
const blob = await response.blob();
const objectUrl = URL.createObjectURL(blob);
downloadFile(objectUrl, filename);
setTimeout(() => URL.revokeObjectURL(objectUrl), 100);
}
大文件分块下载
处理大文件下载时可使用流式处理避免内存问题:
async function downloadLargeFile(url, filename) {
const response = await fetch(url);
const reader = response.body.getReader();
const chunks = [];
while(true) {
const { done, value } = await reader.read();
if(done) break;
chunks.push(value);
}
const blob = new Blob(chunks);
const objectUrl = URL.createObjectURL(blob);
downloadFile(objectUrl, filename);
URL.revokeObjectURL(objectUrl);
}
添加下载进度显示
通过监听 fetch 响应进度实现下载进度条:
async function downloadWithProgress(url, filename) {
const response = await fetch(url);
const contentLength = +response.headers.get('Content-Length');
const reader = response.body.getReader();
let receivedLength = 0;
const chunks = [];
while(true) {
const { done, value } = await reader.read();
if(done) break;
chunks.push(value);
receivedLength += value.length;
console.log(`Downloaded ${(receivedLength/contentLength*100).toFixed(1)}%`);
}
const blob = new Blob(chunks);
downloadFile(URL.createObjectURL(blob), filename);
}
注意事项
- 移动端浏览器可能对程序化下载有不同限制
download属性在某些跨域场景下可能失效- 及时调用
URL.revokeObjectURL()释放内存 - 对于敏感文件建议添加服务器端权限验证







