原生js实现文件上传

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Js实现文件上传功能</title>
 6     <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
 7     <style>
 8         .a-upload {
 9             position: relative;
10             display: inline-block;
11             background: #D0EEFF;
12             border: 1px solid #99D3F5;
13             border-radius: 4px;
14             padding: 4px 12px;
15             overflow: hidden;
16             color: #1E88C7;
17             text-decoration: none;
18             text-indent: 0;
19             line-height: 20px;
20         }
21         .a-upload input {
22             position: absolute;
23             font-size: 100px;
24             right: 0;
25             top: 0;
26             opacity: 0;
27         }
28         .a-upload:hover {
29             background: #AADFFD;
30             border-color: #78C3F3;
31             color: #004974;
32             text-decoration: none;
33         }
34     </style>
35 </head>
36 <body>
37 <form method="post"
38       enctype="multipart/form-data"
39       id="upload">
40     <a href="javascript:;"   id="pic"    class="a-upload">
41         <input type="file"
42                name="file"
43         >
44         点击这里上传文件
45     </a>
46     <input type="button" value="提交" onclick="uploadPic()">
47     <span class="showUrl"></span>
48     <img src="" alt="" class="showPic">
49 </form>
50 </body>
51 <script>
52     function uploadPic() {
53         var form = document.getElementById('upload')
54         var formData = new FormData(form);
55         $.ajax({
56             url:"https://sscpre.boe.com/v1/medical-console/medical/file/upload",
57             type:'post',
58             data:formData,
59             processData:false,
60             success:function (res) {
61                 if(res){
62                     alert('上传成功')
63                 }
64                 $('#pic').val('');
65                 $(".showUrl").html(res);
66                 $(".showPic").attr("src",res);
67             },
68             error:function(err){
69                 alert('网络失败,请稍后再试',err)
70             }
71         })
72     }
73 </script>
74 </html>

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注