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

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

为了在按钮点击时触发文件下载,我们可以使用自定义函数或HTML5的下载属性。

方法1:使用下载属性

下载属性简单地使用锚点标签来准备需要下载的文件的位置。文件的名称可以使用属性值name来设置,如果没有提供,则将使用原始文件名。

语法:

<a download="filename">
  • filename: attribute 指定将要下载的文件的名称。

示例:

<!DOCTYPE html>
<html>
   <body>
      <style>
         p {
         color: green;
         }
      </style>
      <p>How to trigger a file download when 
         clicking an HTML button or JavaScript?
      <p>
         <!-- GFG is the name of the 
            file to be downloaded-->
         <!-- In order to run the code, 
            the location of the file 
            "geeksforgeeks.png" needs to 
            be changed to your local directory,
            both the HTML and downloadable file 
            needs to be present in the same directory -->
         <a href="geeksforgeeks.png" download="GFG">
         <button type="button">Download</button>
         </a>
   </body>
</html>

输出:

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

方法2:使用自定义Javascript函数

  • 首先创建一个文本区域,用于输入所有的文本。
  • 使用createElement属性创建一个锚点标签,然后给它赋予download和href属性。
  • encodeURIComponent 会对具有特殊意义的所有内容进行编码,因此您可以用它来编码URI的组成部分。例如,如果我们有像”Hello: Geek ?”这样的文本,其中有特殊字符,那么encodeURIComponent会对它们进行编码并在进一步使用时附加。
  • data:text/plain; charset=utf-8 是href的属性值(类似于href=””),它指定了该值必须是文本类型,并使用UTF-8编码。click()方法模拟在元素上点击鼠标。
  • 之后,我们只需通过id为’btn’的输入按钮以文本区域中的文本和文件名”GFG.txt”作为参数调用我们的下载函数。

示例:

<!DOCTYPE html>
<html>
   <body>
      <style>
         p {
         color: green;
         }
      </style>
      <p>
          How to trigger a file download when
          clicking an HTML button or JavaScript?
      <p>
         <textarea id="text">
             Welcome to GeeksforGeeks
         </textarea>
         <br/>
         <input type="button" id="btn"
                value="Download" />
         <script>
            function download(file, text) {
             
                //creating an invisible element
                var element = document.createElement('a');
                element.setAttribute('href', 
                'data:text/plain;charset=utf-8, '
                + encodeURIComponent(text));
                element.setAttribute('download', file);
             
                // Above code is equivalent to
                // <a href="path of file" download="file name">
             
                document.body.appendChild(element);
             
                //onClick property
                element.click();
             
                document.body.removeChild(element);
            }
             
            // Start file download.
            document.getElementById("btn")
            .addEventListener("click", function() {
                // Generate download of hello.txt 
                // file with some content
                var text = document.getElementById("text").value;
                var filename = "GFG.txt";
             
                download(filename, text);
            }, false);
         </script>
   </body>
</html>

输出:

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

方法3:使用带有自定义JavaScript函数的Axios库

在这个示例中,我们将使用Axios来下载图像和文件。这需要一些JavaScript的中级知识来运行,在这个示例中我们将使用 Axios库

<!DOCTYPE html>
<!DOCTYPE html>
<html>
   <head>
      <title>Download Images using Axios</title>
      <style> 
         .scroll { 
         height: 1000px; 
         background-color: white; 
         } 
      </style>
   </head>
   <body>
      <p id="dest">
      <h1 style="color: green"> 
         GeeksforGeeks 
      </h1>
      </p> 
      <button onclick="download()">
          Download Image
      </button>
      <p class="scroll"> 
         By clicking the download button 
         will generate a random image.
      </p>
   </body>
   <script src=
"https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js">
   </script>
   <script> 
      function download(){
          axios({
              url:'https://source.unsplash.com/random/500x500',
              method:'GET',
              responseType: 'blob'
      })
      .then((response) => {
             const url = window.URL
             .createObjectURL(new Blob([response.data]));
                    const link = document.createElement('a');
                    link.href = url;
                    link.setAttribute('download', 'image.jpg');
                    document.body.appendChild(link);
                    link.click();
      })
      }
       
   </script>
</html>
</html>

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程