如何透過點選 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.