发送ajax请求实现上传图片显示在网页上

 1 <?php
 2 // 1,通过超全局变量来获取files[上传的图片名称]
 3     $file = $_FILES["files"]
 4 // 2,在通过strrchr来获取图片的格式
 5     $ext = strrchr($file['name'],'.');
 6 // 3,通过uniqid函数随机获取文件名避免名称重复覆盖
 7     $filename = uniqid().$exe;
 8 // 4,可以把获取的图片的名称存在session里面,以免后面用到,这步可写可不写;
 9     session_start();
10     $_SESSION['url'] = $str;19:36:16
11 // 5,通过move_uploaded_file函数把上传获取的图片存在一个文件夹内
12     $bool = move_uploaded_file($file['tmp_name'],'../../static/uploads/'.$filename);
13 // 6,把处理好的图片路径返回给前端
14     if ($bool) { 
15         echo "../static/uploads/" . $fileName; 
16     } else {
17         echo "上传失败"; 
18     };
19 ?>
20 
21 <!DOCTYPE html>
22 <html lang="en">
23 
24 <head>
25     <meta charset="UTF-8">
26     <meta name="viewport" content="width=device-width, initial-scale=1.0">
27     <meta http-equiv="X-UA-Compatible" content="ie=edge">
28     <title>Document</title>
29     <script src="../static/assets/vendors/jquery/jquery.min.js"></script>
30     <script>
31         $(function () {
32             $("#uploadImg").on("change", function () {
33                 // console.log(this.files);
34                 var file = this.files[0];
35                 var data = new FormData();
36                 data.append('file', file);
37                 // console.log(data);
38                 $.ajax({
39                     type: "post",
40                     url: "./api/_addPosts.php",
41                     data: data,
42                     dataType: "json",
43                     success: function (res) {
44                         console.log(res)
45                     }
46                 });
47             });
48         })
49     </script>
50 </head>
51 
52 <body>
53     <input type="file" name="" id="uploadImg">
54 </body>
55 
56 </html>

猜你喜欢

转载自www.cnblogs.com/zbx-boke/p/9383165.html