如何通过点击 HTML 按钮或 JavaScript 触发文件下载?


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

每个人都知道如何使用 input type file 创建文件上传按钮,但很少有开发者知道如何使用JavaScript/JQuery创建文件下载按钮。

本教程将介绍在点击HTML 按钮或 JavaScript 时触发文件下载的各种方法。

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

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

语法

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

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

在上述语法中,我们添加了 download 属性,并将文件名作为 download 属性的值。

参数

  • 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 元素设置 download 属性以及下载的文件名值。

  • 步骤 5 – 将 hidden_a 元素附加到 body。

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

  • 步骤 7 – 使用removeChild() 方法从文档 body 中删除 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() {
         // access the text from the input field
         let user_input = document.getElementById('file_text');
         let texts = user_input.value;
         
         // Create dummy <a> element using JavaScript.
         var hidden_a = document.createElement('a');
         
         // add texts as a href of <a> element after encoding.
         hidden_a.setAttribute('href', 'data:text/plain;charset=utf-8, '+ encodeURIComponent(texts));
         
         // also set the value of the download attribute
         hidden_a.setAttribute('download', "text_file");
         document.body.appendChild(hidden_a);
         
         // click the link element
         hidden_a.click();
         document.body.removeChild(hidden_a);
      }
   </script>
</html>

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

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

语法

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

let results = await axios({
   url: 'file_path',
   method: 'GET',
   responseType: 'blob'
})
// use results as a value of href attribute of <a> tag to download file
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() {
         // get data using 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>

更新于: 2023-09-14

43K+ 次查看

开启你的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.