《PHP應(yīng)用:php實(shí)現(xiàn)base64圖片上傳方式實(shí)例代碼》要點(diǎn):
本文介紹了PHP應(yīng)用:php實(shí)現(xiàn)base64圖片上傳方式實(shí)例代碼,希望對(duì)您有用。如果有疑問,可以聯(lián)系我們。
本例子中沒有采用File Post上傳文件方式!原理一樣,為了更加的理解base64 選擇將其輸出在文本域中,并提交至服務(wù)器!運(yùn)用到項(xiàng)目中建議采用提交File方式.PHP教程
html代碼PHP教程
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>簡單的html5 File測試 for pic2base64</title> <style> </style> <script> window.onload = function(){ var input = document.getElementById("demo_input"); var result= document.getElementById("result"); var img_area = document.getElementById("img_area"); if ( typeof(FileReader) === 'undefined' ){ result.innerHTML = "抱歉,你的瀏覽器不支持 FileReader,請(qǐng)使用現(xiàn)代瀏覽器操作!"; input.setAttribute('disabled','disabled'); }else{ input.addEventListener('change',readFile,false); } } function readFile(){ var file = this.files[0]; //這里我們判斷下類型如果不是圖片就返回 去掉就可以上傳任意文件 if(!/image\/\w+/.test(file.type)){ alert("請(qǐng)確保文件為圖像類型"); return false; } var reader = new FileReader(); reader.readAsDataURL(file); console.log(); reader.onload = function(e){ result.innerHTML = this.result; img_area.innerHTML = '<div class="sitetip">圖片img標(biāo)簽展示:</div>'; } } </script> </head> <body> <form action="file.php" method="post"> <input type="file" value="sdgsdg" id="demo_input" /> <textarea name="img" id="result" rows=30 cols=300></textarea> <p id="img_area"></p> <input type="submit" value="提交"> </form> </body> </html>
PHP功能塊代碼PHP教程
<?php /** * base64圖片上傳 * @param $base64_img * @return array */ $base64_img = trim($_POST['img']); $up_dir = './upload/';//存放在當(dāng)前目錄的upload文件夾下 if(!file_exists($up_dir)){ mkdir($up_dir,0777); } if(preg_match('/^()/', $base64_img, $result)){ $type = $result[2]; if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){ $new_file = $up_dir.date('YmdHis_').'.'.$type; if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){ $img_path = str_replace('../../..', '', $new_file); echo '圖片上傳成功</br>'; }else{ echo '圖片上傳失敗</br>'; } }else{ //文件類型錯(cuò)誤 echo '圖片上傳類型錯(cuò)誤'; } }else{ //文件錯(cuò)誤 echo '文件錯(cuò)誤'; }
實(shí)例效果如下:PHP教程
PHP教程
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持維易PHP.PHP教程
轉(zhuǎn)載請(qǐng)注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/1698.html