簡體   English   中英

如何通過 JavaScript 從 url 下載 .js 文件?

[英]How to download .js file by JavaScript from an url?

我知道這個問題在這個論壇上被問了數百次,但我試圖從我的 Vue 2 應用程序中的 url 下載一個.js文件,但它不起作用。 這是我正在嘗試的:

downloadScript() {
      ApiService.post(`url`).then((res) => {    // axios
        try {
          // Create a new link
          const url = window.URL.createObjectURL(new Blob([res.data.path]));
          const anchor = document.createElement("a");
          anchor.href = url;.js";
          anchor.setAttribute("download", "script.js");
          document.body.appendChild(anchor);
          anchor.click();
        } catch {
         //
        }
      });
    },

這將下載一個文件,該文件只包含我提供給 axios post 請求的 url。

我收到如下 API 響應:

{
    "success": true,
    "path": "https://something.com/files/iq-return.min.js"
}

我必須從path中的文件中下載腳本

new Blob([res.data.path])創建一個 Blob(有點像文件),其中包含您傳遞給它的字符串中的文本。

由於該文本是一個 URL,因此您下載的文件是一個包含該 URL 的文本文件。

如果你想創建一個包含 JavaScript 源代碼的 Blob,那么你需要獲取 JS 源代碼 向 URL 發出 HTTP 請求(例如使用fetch )並將響應主體放入 Blob 中。

(另外:不要將.js附加到您設置href的生成的 URL,這會修改文件的內容!)

當然,如果這是一個跨源請求,這將需要CORS的許可。

如果它不是跨源請求,那么您可以將href屬性設置為res.data.path而無需跳過所有這些箍。

如果我猜對了,您將需要為

你可以這樣做:

 async function downloadFile(url, fileName) { try { const response = await axios.get(url, { responseType: 'arraybuffer' }); fs.writeFileSync(fileName, response.data); } catch (error) { console.error(error); } }

如果文件不存在,writeFileSync 將創建該文件。

如果您更喜歡或需要使用承諾而不是回調,請使用 fs.promises.writeFile

為此,您可以按照以下步驟操作:

  • 使用 Axios 向 API 發出請求以獲取 .js 文件。 使用文件數據創建一個新的 Blob 對象,並使用window.URL.createObjectURL()創建一個對象 URL。

  • 創建一個新的錨元素並將其href屬性設置為對象 URL。 將錨元素的下載屬性設置為所需的文件名。

  • 將錨元素附加到文檔主體。

  • 使用anchor.click()模擬單擊錨點元素以啟動下載。

  • 下載完成后清理對象URL。 您可以通過在finally塊內使用window.URL.revokeObjectURL()撤銷對象 URL 或通過為錨元素上的loadend事件添加事件偵聽器來執行此操作。

以下是如何修改代碼以執行此操作的示例:

downloadScript() {
  ApiService.post(`url`).then((res) => {
    try {
      // Create a new Blob object with the file data
      const blob = new Blob([res.data.path], { type: "application/javascript" });

      // Create an object URL from the Blob
      const url = window.URL.createObjectURL(blob);

      // Create a new anchor element
      const anchor = document.createElement("a");

      // Set the anchor element's href and download attributes
      anchor.href = url;
      anchor.setAttribute("download", "script.js");

      // Append the anchor element to the document body
      document.body.appendChild(anchor);

      // Simulate a click on the anchor element to initiate the download
      anchor.click();

      // Clean up the object URL after the download is completed
      anchor.addEventListener("loadend", () => {
        window.URL.revokeObjectURL(url);
      });
    } catch (error) {
      console.error(error);
    }
  });
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM