萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 純前端導出 TXT/CSV/JSON 文件下載完整方案

現代標準方案:Blob + URL.createObjectURL

無需 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`;
  }
}

現代流式下載:StreamSaver.js(支持 GB 級文件)

<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());

表格導出 CSV 完整示例

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: URIlocation.href = 'data:text/plain,...'長度限制(IE 4KB,現代瀏覽器較大但不可靠),無法指定文件名⚠️ 僅極小文件備用
document.execCommand('SaveAs')IE 專有命令非標準,已移除❌ 棄用
Blob + ObjectURL標準 Web API無✅ 標準方案
File System Access API瀏覽器原生文件系統訪問僅 Chrome/Edge 支持,需用戶手動選擇保存位置🚀 進階場景

File System Access API(未來標準)

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;
copyright © 萬盛學電腦網 all rights reserved