JavaScript 建立和儲存檔案

Harshit Jindal 2023年10月12日
JavaScript 建立和儲存檔案

本教程教授如何在 JavaScript 中建立和儲存檔案。

建立檔案並將它們儲存在伺服器端 NodeJS 上很容易,但在客戶端這樣做的選擇很少。在本教程中,我們編寫了一個自定義函式,幫助我們使用資料建立檔案,然後儲存它。在現代瀏覽器中,我們有一個名為 msSaveOrOpenBlob 的函式,可以幫助我們儲存檔案。但是在舊瀏覽器中,我們首先生成檔案的連結,然後通過在錨標記上新增 download 屬性來下載它。

function downloadFiles(data, file_name, file_type) {
  var file = new Blob([data], {type: file_type});
  if (window.navigator.msSaveOrOpenBlob)
    window.navigator.msSaveOrOpenBlob(file, file_name);
  else {
    var a = document.createElement('a'), url = URL.createObjectURL(file);
    a.href = url;
    a.download = file_name;
    document.body.appendChild(a);
    a.click();
    setTimeout(function() {
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    }, 0);
  }
}

在上面的函式中,我們檢查瀏覽器是否支援 msSaveOrOpenBlob,如果找到,我們使用它來儲存檔案。否則,我們建立一個指向所建立檔案的錨標記。我們將下載屬性新增到錨標記並將該標記附加到文件的正文。我們使用 JavaScript 點選它,觸發下載,並通過這種方式儲存檔案。然後我們從正文中刪除該錨標記並撤銷建立的 URL。

作者: Harshit Jindal
Harshit Jindal avatar Harshit Jindal avatar

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

LinkedIn