1. 程式人生 > >發送ajax請求實現上傳圖片顯示在網頁上

發送ajax請求實現上傳圖片顯示在網頁上

sse set url orm 顯示 ini session load file

 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>

發送ajax請求實現上傳圖片顯示在網頁上