首頁  >  文章  >  web前端  >  點擊HTML按鈕或JavaScript時如何觸發檔案下載?

點擊HTML按鈕或JavaScript時如何觸發檔案下載?

王林
王林轉載
2023-09-12 12:49:02989瀏覽

點擊HTML按鈕或JavaScript時如何觸發檔案下載?

現今,許多應用程式允許使用者進行檔案的上傳下載。例如,抄襲檢測工具允許使用者上傳一個包含一些文字的文件檔案。然後,它會檢查抄襲並產生報告,用戶可以下載該報告。

每個人都知道使用input type file來建立一個上傳檔案按鈕,但是很少有開發者知道如何使用JavaScript/ JQuery來建立一個檔案下載按鈕。

本教學將教導點擊HTML按鈕或JavaScript時觸發檔案下載的各種方法。

使用HTML的標籤和download屬性,在按鈕點擊時觸發檔案下載

每當我們在標籤上新增download屬性時,我們可以將標籤當作檔案下載按鈕使用。我們需要將檔案的URL作為href屬性的值傳遞,以允許使用者在點擊連結時下載特定的檔案。

文法

使用者可以按照下面的語法使用標籤建立一個檔案下載按鈕。

<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(); 

在上述語法中,我們對文字進行了編碼,以將其附加到文件中,並使用標籤進行建立。

演算法

  • 第一步 - 透過存取HTML輸入來取得文字。

  • Step 2 − Create a custom HTML 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或檔案路徑取得數據,然後將該數據設定為標籤的href屬性的值。此外,我們將使用setAttribute()方法為標籤新增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點擊了
元素以觸發檔案下載。 ###
<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>
###

以上是點擊HTML按鈕或JavaScript時如何觸發檔案下載?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除