网页 文件上传功能实现的 两种方式

1-------------xhr  实现-----------

 1 <!DOCTYPE html>
 2 <html lang="en">
 3   <head>
 4     <meta charset="UTF-8" />
 5     <meta http-equiv="X-UA-Compatible" content="IE=edge" />
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 7     <title>Document</title>
 8     <link rel="stylesheet" href="./lib/bootstrap.css" />
 9     <script src="./lib/jquery.js"></script>
10   </head>
11   <body>
12     <input type="file" name="" id="file1" />
13     <button id="btn">上传文件</button>
14     <!-- 进度条 -->
15     <div class="progress" style=" 300px; margin: 15px 10px">
16       <div
17         class="progress-bar progress-bar-striped active"
18         style=" 0%"
19         id="percent"
20       >
21         0%
22       </div>
23     </div>
24     <br />
25     <img src="" id="img" />
26     <script>
27       // -----------111111---------------------
28       // 获取上传元素
29       let btn = document.getElementById("btn");
30       btn.addEventListener("click", function () {
31         //   获取文件列表  利用.files属性
32         let files = document.querySelector("#file1").files;
33         if (files.length <= 0) {
34           return alert("请上传文件后点击提交");
35         }
36         // ---------222222-------------------------
37         // 创建一个 formData
38         let fd = new FormData();
39         // 往里面追加 文件
40         fd.append("avatar", files[0]);
41         // -------33333---------------
42         // 使用xhr 发起文件请求
43         let xhr = new XMLHttpRequest();
44         // ------------------------------------------
45         // 监听 xhr.upload 的 onprogress 事件
46         xhr.upload.onprogress = function (e) {
47           if (e.lengthComputable) {
48             let percentComplete = Math.ceil((e.loaded / e.total) * 100);
49             console.log(percentComplete);
50             $("#percent")
51               // 样式
52               .attr("style", "" + percentComplete + "%")
53               // 设置内容
54               .html(percentComplete + "%");
55           }
56         };
57         // -----------------------------------------
58         xhr.upload.onload = function () {
59           $("#percent")
60             // 移除上传中的类样式
61             .removeClass()
62             // 添加上传完成的类样式
63             .addClass("progress-bar progress-bar-success");
64         };
65         // --------------------------------------
66         xhr.open("POST", "http://www.liulongbin.top:3006/api/upload/avatar");
67         xhr.send(fd);
68         // ----------监听加载状态-------------------------
69         xhr.onload = function () {
70           if (this.status === 200) {
71             let data = JSON.parse(xhr.responseText);
72             console.log(data);
73             if (data.status == 200) {
74               document.querySelector("#img").src =
75                 "http://www.liulongbin.top:3006" + data.url;
76             } else {
77               // 打印错误信息
78               console.log(data.message);
79             }
80           }
81         };
82       });
83     </script>
84   </body>
85 </html>

2------------ajax 实现----------------

 1 <!DOCTYPE html>
 2 <html lang="en">
 3   <head>
 4     <meta charset="UTF-8" />
 5     <meta http-equiv="X-UA-Compatible" content="IE=edge" />
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 7     <title>Document</title>
 8     <script src="./lib/jquery.js"></script>
 9   </head>
10   <body>
11     <!-- 结构 -->
12     <input type="file" id="file1" />
13     <button id="btn">上传文件</button>
14     <br />
15     <img src="./loading.gif" id="loading" style="display: none" />
16     <!-- js -->
17     <script>
      //为上传文件按钮添加添加事件 18 $("#btn").on("click", function () {
       //获取文件的列表 并判断有无文件
19 let files = $("#file1")[0].files; 20 if (files.length <= 0) { 21 return alert("请上传文档再点击哦"); 22 } 23 //新建formData 存放文件 24 let fd = new FormData(); 25 fd.append("avartar", files[0]); 26 //-------------发起ajax post请求---上传文件----------------- 27 $.ajax({ 28 type: "POST", 29 url: "http://www.liulongbin.top:3006/api/upload/avatar", 30 data: fd, 31 // 这两个属性必须要 否则会报错------ 32 contentType: false,//------------------->注意点 33 processData: false,//---------------------->注意点 34 // -------------------- 35 success: function (res) { 36 console.log(res); 37 }, 38 }); 39 });
      //当 AJAX 请求开始时,显示“加载中”的图片
40 $(document).ajaxStart(function () {42 $("#loading").show(); 43 });
      //当所有 AJAX 请求完成时 隐藏 加载中的图片
44 $(document).ajaxStop(function () { 45 $("#loading").hide(); 46 }); 47 </script> 48 </body> 49 </html>
原文地址:https://www.cnblogs.com/ndh074512/p/14815766.html