無需 Flash、無需服務端,純前端生成文件並觸發下載,兼容所有現代瀏覽器。
/**
* 觸發文件下載
* @param {string} content - 文件內容
* @param {string} filename - 文件名(含擴展名)
* @param {string} mimeType - MIME 類型
*/
function downloadFile(content, filename, mimeType = 'text/plain;charset=utf-8') {
// 1. 創建 Blob
const blob = new Blob([content], { type: mimeType });
// 2. 創建 Object URL
const url = URL.createObjectURL(blob);
// 3. 創建隱藏鏈接觸發下載
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.style.display = 'none';
// 4. 觸發點擊
document.body.appendChild(a);
a.click();
// 5. 清理
setTimeout(() => {
document.body.removeChild(a);
URL.revokeObjectURL(url); // 釋放內存
}, 100);
}
// 使用示例
downloadFile('Hello World', 'hello.txt');
downloadFile('姓名,年齡\n張三,25\n李四,30', 'users.csv', 'text/csv;charset=utf-8');
downloadFile(JSON.stringify({a:1,b:2}, null, 2), 'data.json', 'application/json');
// UTF-8 BOM 防止 Excel 打開 CSV 亂碼
function downloadCSV(content, filename) {
const BOM = '\uFEFF'; // UTF-8 BOM
downloadFile(BOM + content, filename, 'text/csv;charset=utf-8');
}
// 或者用 TextEncoder(現代瀏覽器)
function downloadFileModern(content, filename, mimeType) {
const blob = new Blob([new TextEncoder().encode(content)], { type: mimeType });
// ... 後續同上
}
async function downloadLargeFile(generator, filename, mimeType) {
// generator: 異步生成器 function* () { yield chunk1; yield chunk2; ... }
const chunks = [];
for await (const chunk of generator()) {
chunks.push(chunk);
// 可選:定期釋放內存
if (chunks.length > 100) {
const blob = new Blob(chunks, { type: mimeType });
// 這裡需配合 File System Access API 或 StreamSaver.js 實現流式下載
}
}
// 小文件直接合併
downloadFile(chunks.join(''), filename, mimeType);
}
// 示例:生成 100 萬行 CSV
function* generateBigCSV() {
yield 'id,name,value\n';
for (let i = 0; i < 1e6; i++) {
if (i % 10000 === 0) yield ''; // 讓出事件循環
yield `${i},name${i},${Math.random()}\n`;
}
}
<script src="https://cdn.jsdelivr.net/npm/streamsaver@2.0.5/StreamSaver.min.js"></script>
async function streamDownload(filename, asyncIterator) {
const fileStream = streamSaver.createWriteStream(filename);
const writer = fileStream.getWriter();
const encoder = new TextEncoder();
try {
for await (const chunk of asyncIterator) {
await writer.write(encoder.encode(chunk));
}
} finally {
await writer.close();
}
}
// 使用
streamDownload('big-data.csv', generateBigCSV());
function exportTableToCSV(tableSelector, filename) {
const $table = $(tableSelector);
const rows = [];
// 表頭
const headers = [];
$table.find('thead th').each(function() {
headers.push('"' + $(this).text().trim().replace(/"/g, '""') + '"');
});
rows.push(headers.join(','));
// 數據行
$table.find('tbody tr').each(function() {
const cells = [];
$(this).find('td').each(function() {
cells.push('"' + $(this).text().trim().replace(/"/g, '""') + '"');
});
rows.push(cells.join(','));
});
downloadCSV(rows.join('\n'), filename);
}
// 使用
$('#export-btn').click(() => exportTableToCSV('#data-table', 'export_' + Date.now() + '.csv'));
| 方案 | 原理 | 缺陷 | 現狀 |
|---|---|---|---|
| Downloadify (Flash) | Flash 橋接文件保存對話框 | 需 Flash 插件,2020 年停止支持 | ❌ 棄用 |
| data: URI | location.href = 'data:text/plain,...' | 長度限制(IE 4KB,現代瀏覽器較大但不可靠),無法指定文件名 | ⚠️ 僅極小文件備用 |
| document.execCommand('SaveAs') | IE 專有命令 | 非標準,已移除 | ❌ 棄用 |
| Blob + ObjectURL | 標準 Web API | 無 | ✅ 標準方案 |
| File System Access API | 瀏覽器原生文件系統訪問 | 僅 Chrome/Edge 支持,需用戶手動選擇保存位置 | 🚀 進階場景 |
async function saveFileModern(content, suggestedName) {
try {
const handle = await window.showSaveFilePicker({
suggestedName,
types: [{
description: 'Text Files',
accept: { 'text/plain': ['.txt'], 'text/csv': ['.csv'], 'application/json': ['.json'] }
}]
});
const writable = await handle.createWritable();
await writable.write(content);
await writable.close();
} catch (err) {
if (err.name !== 'AbortError') console.error(err);
// 用戶取消或不支持時降級
downloadFile(content, suggestedName);
}
}
// 特性檢測降級
const saveFile = 'showSaveFilePicker' in window ? saveFileModern : downloadFile;