如何在单击 HTML 按钮或 JavaScript 时触发文件下载?

javascripthtmlweb developmentfront end technology

如今,许多应用程序都允许用户上传下载文件。例如,抄袭检查工具允许用户上传包含一些文本的文档文件。之后,它会检查是否存在抄袭并生成报告,然后用户可以下载。

每个人都知道使用输入类型文件创建上传文件按钮,但很少有开发人员知道使用 JavaScript/JQuery 创建文件下载按钮。

本教程将教授单击 HTML 按钮或 JavaScript 时触发文件下载的各种方法。

使用带有 HTML <a> 标签的下载属性在单击按钮时触发文件下载

每当我们将下载属性添加到 <a>标签,我们可以将 <a> 标签用作文件下载按钮。我们需要将文件 URL 作为 href 属性的值传递,以允许用户在点击链接时下载任何特定文件。

语法

用户可以按照以下语法使用 <a> 标签创建文件下载按钮。

<a href = "file_path" download = "file_name">

在上述语法中,我们添加了下载属性和文件名作为下载属性的值。

参数

  • file_path – 这是我们希望用户下载的文件路径。

示例 1

在下面的示例中,我们获取了图像 URL 并将其作为 HTML <a> 标签的 href 属性的值传递。我们已将下载按钮用作 <a> 标签的锚文本。

每当用户单击按钮时,他们都可以看到它会触发文件下载。

<html>
   <body>
      <h3> Using the <i> download attribute of <a> tag </i> to create file download button using JavaScript. </h3>
      <p> Click the below button to download the image file </p>
      <a href = "https://images.pexels.com/photos/268533/pexels-photo-268533.jpeg?cs=srgb&dl=pexels-pixabay-268533.jpg&fm=jpg"
      Download = "test_image">
         <button type = "button"> Download </button>
      </a>
   </body>
</html>

使用 window.open() 方法

window.open() 方法在新选项卡中打开 URL。我们可以将 URL 作为 open() 方法的参数传递。

如果 open() 方法无法打开 URL,则会触发文件下载。

语法

用户可以按照以下语法使用 window.open() 方法创建文件下载按钮。

window.open("file_url")

在上述语法中,我们将文件 URL 作为 window.open() 方法的参数传递。

示例 2

在下面的示例中,每当用户单击按钮时,都会触发 downloadFile() 函数。在 downloadFile() 函数中,window.open() 方法触发文件下载。

<html>
<body>
   <h3> Using the <i> window.open() method </i> to create a file download button using JavaScript. </h3>
   <p> Click the below button to download the image file </p>
   <button type = "button" onclick = "downloadFile()"> Download </button>
</body>
   <script>
      function downloadFile() {
         window.open("https://images.pexels.com/photos/268533/pexels-photo-268533.jpeg?cs=srgb&dl=pexels-pixabay-268533.jpg&fm=jpg")
      }
   </script>
</html>

获取用户输入,使用其创建文件并允许用户下载该文件

此方法将允许用户在输入字段中输入文本。之后,使用输入的文本,我们将创建一个新文件并允许用户下载该文件。

语法

用户可以按照以下语法从自定义文本创建文件并允许用户下载它。

var hidden_​​a = document.createElement('a');
hidden_​​a.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(texts));
hidden_​​a.setAttribute('download', "text_file");
document.body.appendChild(hidden_​​a); hidden_​​a.click();

在上述语法中,我们对文本进行编码以将其附加到文件中,并使用 <a> 标记来创建它。

算法

  • 步骤 1 - 通过访问 HTML 输入从输入中获取文本。

  • 步骤 2 - 使用 JavaScript createElement() 方法创建自定义 HTML <a> 标记。

  • 步骤 3 - 使用 setAttribute() 方法,并为 hidden_​​a HTML 元素设置 href 属性。使用编码文本作为 href 属性的值。

  • 步骤 4 − 再次使用 setAttribute() 方法,将下载属性与下载文件名值一起设置为 hidden_​​a 元素。

  • 步骤 5 − 将 hidden_​​a 元素附加到正文。

  • 步骤 6 − 使用 click() 方法触发对 hidden_​​a 元素的点击。当它调用 click() 方法时,它开始下载。

  • 第 7 步 - 使用 removeChild() 方法从文档主体中删除 hidden_​​a 元素。

示例 3

在下面的示例中,用户可以在输入字段中输入任何自定义文本,然后单击按钮以使用 JavaScript 触发文件下载。我们已经实现了上述算法来触发文件下载。

<html>
<body>
   <h3> Create the file from the custom text and allow users to download that file </h3>
   <p> Click the below button to download the file with custom text. </p>
   <input type = "text" id = "file_text" value = "Entetr some text here.">
   <button type = "button" onclick = "startDownload()"> Download </button>
</body>
   <script>
      function startDownload() {
        // 从输入字段访问文本
        let user_input = document.getElementById('file_text');
        let texts = user_input.value;
        
        // 使用 JavaScript 创建虚拟 <a> 元素。
        var hidden_​​a = document.createElement('a');
        
        // 编码后将文本添加为​​ <a> 元素的 href。
        hidden_​​a.setAttribute('href', 'data:text/plain;charset=utf-8, '+ encodeURIComponent(texts));
        
        // 还设置下载属性的值
        hidden_​​a.setAttribute('download', "text_file");
        document.body.appendChild(hidden_​​a);
        
        // 单击链接元素
        hidden_​​a.click();
        document.body.removeChild(hidden_​​a);
      }
   </script>
</html>

使用 axios 库创建下载文件按钮

axios 库允许我们从任何 URL 获取数据。因此,我们将从任何 URL 或文件路径获取数据,然后,我们将该数据设置为 <a> 标签的 href 属性的值。此外,我们将使用 setAttribute() 方法向 <a> 标签添加下载属性,并触发 click() 方法以开始文件下载。

语法

用户可以按照以下语法使用 axios 通过 JavaScript 触发文件下载。

let results = await axios({
   url: 'file_path',
   method: 'GET',
   responseType: 'blob'
})
// 使用 results 作为 <a> 标签 href 属性的值来下载文件
hidden_​​a.href = window.URL.createObjectURL(new Blob([results.data]));

在上面的语法中,axios.get() 方法允许我们从 results 变量中存储的 file_path 中获取数据。之后,我们使用新的 Blob() 构造函数将数据转换为 Bolb 对象。

示例 4

在下面的示例中,我们使用 axios 从 URL 中获取数据,将其转换为 Blob 对象,并将其设置为 href 属性的值。

之后,我们从 JavaScript 中单击 <a> 元素以触发文件下载。

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/axios/1.3.1/axios.min.js"> </script>
</head>
<body>
   <h3> Using the <i> axios library </i> to trigger a download file. </h3>
   <p> Click the below button to download the file with custom text. </p>
   <button type = "button" onclick = "startDownload()"> Download </button>
</body>
   <script>
      async function startDownload() {
         // 使用 axios 获取数据
         let results = await axios({
            url: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTZ4gbghQxKQ00p3xIvyMBXBgGmChzLSh1VQId1oyhYrgir1bkn812dc1LwOgnajgWd-Yo&usqp=CAU',
            method: 'GET',
            responseType: 'blob'
         })
         let hidden_a = document.createElement('a');
         hidden_a.href = window.URL.createObjectURL(new Blob([results.data]));
         hidden_a.setAttribute('download', 'download_image.jpg');
         document.body.appendChild(hidden_a);
         hidden_a.click();
      }
   </script>
</html>

相关文章