首页 > 文章列表 > 点击HTML按钮或JavaScript时如何触发文件下载?

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

JavaScript 文件下载 关键词:HTML按钮
373 2023-09-20

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

每个人都知道使用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 – 这是我们希望用户下载的文件路径。

Example 1

的翻译为:

示例 1

在下面的示例中,我们将图像URL作为HTML 标签的href属性的值传递。我们使用下载按钮作为标签的锚文本

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

<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()方法的参数传递。

Example 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>标签进行创建。

算法

  • 第一步 - 通过访问HTML输入来获取文本。

  • Step 2 − Create a custom HTML <a> tag using JavaScript createElement() method.

  • 步骤 3 − 使用setAttribute()方法,为hidden_a HTML元素设置href属性。将编码后的文本作为href属性的值。

  • 步骤 4 − 再次使用 setAttribute() 方法,并将 download 属性设置为隐藏元素 hidden_a 的下载文件名值。

  • 第五步 - 将hidden_a元素追加到body中。

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

  • 第7步 - 使用removeChild()方法从文档主体中移除hidden_a元素。

Example 3

的中文翻译为:

示例3

In the example below, users can enter any custom text in the input field and click the button to trigger file download using JavaScript. We have implemented the above algorithm to trigger a file download.

<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 获取数据。之后,我们使用 new Blob() 构造函数将数据转换为 Blob 对象。

Example 4

的中文翻译为:

示例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>