简体   繁体   English

如何通过 JavaScript 从 url 下载 .js 文件?

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

I know this question is asked hundreds of time in this forum, But I'm trying to download a .js file from an url in my Vue 2 application, but it's not working.我知道这个问题在这个论坛上被问了数百次,但我试图从我的 Vue 2 应用程序中的 url 下载一个.js文件,但它不起作用。 Here is what I'm trying:这是我正在尝试的:

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 {
         //
        }
      });
    },

This downloads a file which consists nothing but the url I've provided to the axios post request.这将下载一个文件,该文件只包含我提供给 axios post 请求的 url。

I'm getting API response like following:我收到如下 API 响应:

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

I've to donwload the script in a file from the path我必须从path中的文件中下载脚本

new Blob([res.data.path]) creates a Blob (which is sort-of-like-a-file) containing the text in the string you pass it. new Blob([res.data.path])创建一个 Blob(有点像文件),其中包含您传递给它的字符串中的文本。

Since that text is a URL, the file you download is a text file containing that URL.由于该文本是一个 URL,因此您下载的文件是一个包含该 URL 的文本文件。

If you want to create a Blob containing the JavaScript source code, then you need to get the JS source code .如果你想创建一个包含 JavaScript 源代码的 Blob,那么你需要获取 JS 源代码 Make an HTTP request to the URL (eg with fetch ) and put the response body in the Blob.向 URL 发出 HTTP 请求(例如使用fetch )并将响应主体放入 Blob 中。

(Aside: don't append .js to the generated URL with you set href , that modifies the contents of the file!) (另外:不要将.js附加到您设置href的生成的 URL,这会修改文件的内容!)

This will, of course, require permission from CORS if this is a cross-origin request.当然,如果这是一个跨源请求,这将需要CORS的许可。

If it isn't a cross-origin request then you can just set the href attribute to res.data.path without leaping through all these hoops.如果它不是跨源请求,那么您可以将href属性设置为res.data.path而无需跳过所有这些箍。

If I got you right you will need to do a separate get request for the如果我猜对了,您将需要为

you can do something like this:你可以这样做:

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

the writeFileSync will create the file if it does not exist.如果文件不存在,writeFileSync 将创建该文件。

if you prefer or need to use promises instead of callbacks use fs.promises.writeFile如果您更喜欢或需要使用承诺而不是回调,请使用 fs.promises.writeFile

To do this, you can follow these steps:为此,您可以按照以下步骤操作:

  • Make a request to the API using Axios to get the.js file.使用 Axios 向 API 发出请求以获取 .js 文件。 Create a new Blob object with the file data and create an object URL using the window.URL.createObjectURL() .使用文件数据创建一个新的 Blob 对象,并使用window.URL.createObjectURL()创建一个对象 URL。

  • Create a new anchor element and set its href attribute to the object URL.创建一个新的锚元素并将其href属性设置为对象 URL。 Set the download attribute of the anchor element to the desired file name.将锚元素的下载属性设置为所需的文件名。

  • Append the anchor element to the document body.将锚元素附加到文档主体。

  • Simulate a click on the anchor element using anchor.click() to initiate the download.使用anchor.click()模拟单击锚点元素以启动下载。

  • Clean up the object URL after the download is completed.下载完成后清理对象URL。 You can do this by revoking the object URL using window.URL.revokeObjectURL() inside a finally block or by adding an event listener for the loadend event on the anchor element.您可以通过在finally块内使用window.URL.revokeObjectURL()撤销对象 URL 或通过为锚元素上的loadend事件添加事件侦听器来执行此操作。

Here is an example of how you can modify your code to do this:以下是如何修改代码以执行此操作的示例:

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