當前代碼功能有一些缺陷,可以關注最新的博客進行查看(https://www.cnblogs.com/yulongcode/p/12442054.html),如果您有興趣,可以自己研究研究,歡迎溝通交流
====================================================================================
涉及知識:base64處理圖片,ajax,js,thinkphp
效果圖:
代碼實現:
html:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>showImages</title> 6 <style type="text/css"> 7 .float{ 8 float:left; 9 width : 200px; 10 height: 200px; 11 overflow: hidden; 12 border: 1px solid #CCCCCC; 13 border-radius: 10px; 14 padding: 5px; 15 margin: 5px; 16 } 17 img{ 18 position: relative; 19 } 20 .result{ 21 width: 200px; 22 height: 200px; 23 text-align: center; 24 box-sizing: border-box; 25 } 26 #file_input{ 27 display: none; 28 } 29 .delete{ 30 width: 200px; 31 height:200px; 32 position: absolute; 33 text-align: center; 34 line-height: 200px; 35 z-index: 10; 36 font-size: 30px; 37 background-color: rgba(255,255,255,0.8); 38 color: #777; 39 opacity: 0; 40 transition-duration: :0.7s; 41 -webkit-transition-duration: 0.7s; 42 } 43 .delete:hover{ 44 cursor: pointer; 45 opacity: 1; 46 } 47 </style> 48 <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> 49 <script type="text/javascript"> 50 window.onload = function(){ 51 var input = document.getElementById("file_input"); 52 var result; 53 var dataArr = []; // 儲存所選圖片的結果(文件名和base64數據) 54 var fd; //FormData方式發送請求 55 var oSelect = document.getElementById("select"); 56 var oAdd = document.getElementById("add"); 57 var oSubmit = document.getElementById("submit"); 58 var oInput = document.getElementById("file_input"); 59 60 if(typeof FileReader==='undefined'){ 61 alert("抱歉,你的瀏覽器不支持 FileReader"); 62 input.setAttribute('disabled','disabled'); 63 }else{ 64 input.addEventListener('change',readFile,false); 65 } //handler 66 67 function readFile(){ 68 fd = new FormData(); 69 var iLen = this.files.length; 70 var index = 0; 71 for(var i=0;i<iLen;i++){ 72 if (!input['value'].match(/.jpg|.gif|.png|.jpeg|.bmp/i)){ //判斷上傳文件格式 73 return alert("上傳的圖片格式不正確,請重新選擇"); 74 } 75 var reader = new FileReader(); 76 reader.index = i; 77 fd.append(i,this.files[i]); 78 reader.readAsDataURL(this.files[i]); //轉成base64 79 reader.fileName = this.files[i].name; 80 81 reader.onload = function(e){ 82 var imgMsg = { 83 name : this.fileName,//獲取文件名 84 base64 : this.result //reader.readAsDataURL方法執行完后,base64數據儲存在reader.result里 85 } 86 dataArr.push(imgMsg); 87 result = '<div class="delete">delete</div><div class="result"><img src="'+this.result+'" alt=""/></div>'; 88 var div = document.createElement('div'); 89 div.innerHTML = result; 90 div['className'] = 'float'; 91 div['index'] = index; 92 document.getElementsByTagName('body')[0].appendChild(div); //插入dom樹 93 var img = div.getElementsByTagName('img')[0]; 94 img.onload = function(){ 95 var nowHeight = ReSizePic(this); //設置圖片大小 96 this.parentNode.style.display = 'block'; 97 var oParent = this.parentNode; 98 if(nowHeight){ 99 oParent.style.paddingTop = (oParent.offsetHeight - nowHeight)/2 + 'px'; 100 } 101 } 102 103 div.onclick = function(){ 104 this.remove(); // 在頁面中刪除該圖片元素 105 delete dataArr[this.index]; // 刪除dataArr對應的數據 106 107 } 108 index++; 109 } 110 } 111 } 112 113 114 function send(){ 115 var submitArr = []; 116 for (var i = 0; i < dataArr.length; i++) { 117 if (dataArr[i]) { 118 submitArr.push(dataArr[i]); 119 } 120 } 121 // console.log('提交的數據:'+JSON.stringify(submitArr)) 122 $.ajax({ 123 type : "post", 124 url : "{:URL('index/Index/index')}", 125 data : { 126 img : JSON.stringify(submitArr) 127 }, 128 // processData: false, //用FormData傳fd時需有這兩項 129 // contentType: false, 130 success : function(data){ 131 // console.log('返回的數據:'+data); 132 if(data ==1) 133 { 134 alert('yes'); 135 }else { 136 alert('no'); 137 } 138 } 139 }) 140 } 141 142 oSelect.onclick=function(){ 143 oInput.value = ""; // 先將oInput值清空,否則選擇圖片與上次相同時change事件不會觸發 144 //清空已選圖片 145 $('.float').remove(); 146 dataArr = []; 147 index = 0; 148 oInput.click(); 149 } 150 151 oAdd.onclick=function(){ 152 oInput.value = ""; // 先將oInput值清空,否則選擇圖片與上次相同時change事件不會觸發 153 oInput.click(); 154 } 155 156 157 oSubmit.onclick=function(){ 158 if(!dataArr.length){ 159 return alert('請先選擇文件'); 160 } 161 send(); 162 } 163 } 164 /* 165 用ajax發送fd參數時要告訴jQuery不要去處理發送的數據, 166 不要去設置Content-Type請求頭才可以發送成功,否則會報“Illegal invocation”的錯誤, 167 也就是非法調用,所以要加上“processData: false,contentType: false,” 168 * */ 169 170 function ReSizePic(ThisPic) { 171 var RePicWidth = 200; //這里修改為您想顯示的寬度值 172 173 var TrueWidth = ThisPic.width; //圖片實際寬度 174 var TrueHeight = ThisPic.height; //圖片實際高度 175 176 if(TrueWidth>TrueHeight){ 177 //寬大於高 178 var reWidth = RePicWidth; 179 ThisPic.width = reWidth; 180 //垂直居中 181 var nowHeight = TrueHeight * (reWidth/TrueWidth); 182 return nowHeight; //將圖片修改后的高度返回,供垂直居中用 183 }else{ 184 //寬小於高 185 var reHeight = RePicWidth; 186 ThisPic.height = reHeight; 187 } 188 } 189 </script> 190 </head> 191 <body> 192 <div class="container"> 193 <label>請選擇一個圖像文件:</label> 194 <button id="select">(重新)選擇圖片</button> 195 <button id="add">(追加)圖片</button> 196 197 <form action="" > 198 <input type="file" id="file_input" name="image[]" multiple/> 199 <!--用input標簽並選擇type=file,記得帶上multiple,不然就只能單選圖片了--> 200 <button id="submit">提交</button> 201 </form> 202 203 </div> 204 </body> 205 </html>
php:
<?php namespace app\index\controller; use think\Controller; use think\Db; class Index extends Controller { public function index() { if(request()->isAjax()) { $img = request()->post('img'); //接收圖片信息 $arr = json_decode($img,true); //轉成數組 $ImgUrl = []; for($i=0;$i<count($arr);$i++) { $houzhui = substr(strrchr($arr[$i]['name'], '.'), 1);//獲取文件后綴名 $image = $arr[$i]['base64']; //這里的圖片名稱就是你存入數據庫時的圖片名稱 $imageName = date("His",time())."_".rand(1111,9999).'.'.$houzhui; // 判斷是否有逗號 如果有就截取后半部分 if (strstr($image,",")){ $image = explode(',',$image); $image = $image[1]; } //圖片保存路徑,可根據使用框架目錄的不同自定義目錄 $path = ROOT_PATH . 'public' . DS .'static'. DS .date("Ymd",time()); // 判斷目錄是否存在 不存在就創建 並賦予777權限 if (!is_dir($path)){ //判斷目錄是否存在 不存在就創建 mkdir($path,0777,true); } $imageSrc= $path."/". $imageName; // 生成圖片 返回的是字節數 $r = file_put_contents($imageSrc, base64_decode($image)); if (!$r) { $ImgUrl[$i] = "===圖片生成失敗==="; }else{ $ImgUrl[$i] = $imageName; } } //$ImgUrl 即為上傳之后的圖片名稱,是逗號隔開的字符串 $ImgUrl = implode(',',$ImgUrl); //將字符串存入數據庫 $data = Db::table('testimg')->insert(['val'=>$ImgUrl]); if($data) { return 1; }else{ return 0; } }else{ return view(); } } }
over!over!over!