如何使用JavaScript/jQuery下载文件

如何使用JavaScript/jQuery下载文件

假设你想在点击一个链接时下载一个文件。为了下载文件,我们在这里提到了实施以及文件夹结构,你可以看到文件的位置。

步骤:

  • 在正常的HTML页面上创建一个锚定标签链接。我们想在点击锚标签链接时下载一个文件(下载此文件)。
<!DOCTYPE html>
<html>
  
<head>
    <title>
        Download File Using 
        JavaScript/jQuery
    </title>
</head>
  
<body>
    <h1>
        Download File Using 
        JavaScript/jQuery
    </h1>
  
    <a id="link" href="#">
        Download this file
    </a>
</body>
  
</html>
  • 提供以下JavaScript代码。
$(document).ready(function () {
      $("#link").click(function (e) {
          e.preventDefault();
          window.location.href = "File/randomfile.docx";
      });
});

// Note: url= your file path

  • 注意:用你的文件路径替换上述URL。
    实施和文件夹结构如下所示。

如何使用JavaScript/jQuery下载文件?

示例:

<!DOCTYPE html>
<html>
  
<head>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
</head>
  
<body>
    <h1>
        Download File Using 
        JavaScript/jQuery
    </h1>
      
    <h3>
        For Downloading, Click 
        on the below link.
    </h3>
      
    <a id="link" href="no-script.html">
        Download this file
    </a>
      
    <script>
        (document).ready(function () {
            ("#link").click(function (e) {
                e.preventDefault();
                  
                window.location.href 
                    = "File/randomfile.docx";
            });
        });
    </script>
</body>
  
</html>

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程