PHP實現本地圖片轉base64格式並上傳
阿新 • • 發佈:2020-05-30
我們在開發系統時,處理圖片上傳是不可避免的,例如使用thinkphp的肯定很熟悉import("@.ORG.UploadFile");的上傳方式,今天我們來講一個使用html5 base64上傳圖片的方法。
主要是用到html5 FileReader的介面,既然是html5的,所支援的瀏覽器我就不多說啦
可以大概的講一下思路,其實也挺簡單。選擇了圖片之後,js會先把已選的圖片轉化為base64格式,然後通過ajax上傳到伺服器端,伺服器端再轉化為圖片,進行儲存的一個過程。
咱們先看看前端的程式碼。
html部分
<input type="file" id="imagesfile">
js部分
$("#imagesfile").change(function (){ var file = this.files[0]; //用size屬性判斷檔案大小不能超過5M ,前端直接判斷的好處,免去伺服器的壓力。 if( file.size > 5*1024*1024 ){ alert( "你上傳的檔案太大了!" ) } //好東西來了 var reader=new FileReader(); reader.onload = function(){ // 通過 reader.result 來訪問生成的 base64 DataURL var base64 = reader.result; //列印到控制檯,按F12檢視 console.log(base64); //上傳圖片 base64_uploading(base64); } reader.readAsDataURL(file); }); //AJAX上傳base64 function base64_uploading(base64Data){ $.ajax({ type: 'POST',url: "上傳介面路徑",data: { 'base64': base64Data },dataType: 'json',timeout: 50000,success: function(data){ console.log(data); },complete:function() {},error: function(xhr,type){ alert('上傳超時啦,再試試'); } }); }
其實前端的程式碼也並不複雜,主要是使用了new FileReader();的介面來轉化圖片,new FileReader();還有其他的介面,想了解更多的介面使用的童鞋,自行谷歌搜尋new FileReader();。
接下來,那就是伺服器端的程式碼了,上面的demo,是用thinkphp為框架編寫的,但其他框架也基本通用的。
function base64imgsave($img){ //資料夾日期 $ymd = date("Ymd"); //圖片路徑地址 $basedir = 'upload/base64/'.$ymd.''; $fullpath = $basedir; if(!is_dir($fullpath)){ mkdir($fullpath,0777,true); } $types = empty($types)? array('jpg','gif','png','jpeg'):$types; $img = str_replace(array('_','-'),array('/','+'),$img); $b64img = substr($img,100); if(preg_match('/^(data:\s*image\/(\w+);base64,)/',$b64img,$matches)){ $type = $matches[2]; if(!in_array($type,$types)){ return array('status'=>1,'info'=>'圖片格式不正確,只支援 jpg、gif、png、jpeg哦!','url'=>''); } $img = str_replace($matches[1],'',$img); $img = base64_decode($img); $photo = '/'.md5(date('YmdHis').rand(1000,9999)).'.'.$type; file_put_contents($fullpath.$photo,$img); $ary['status'] = 1; $ary['info'] = '儲存圖片成功'; $ary['url'] = $basedir.$photo; return $ary; } $ary['status'] = 0; $ary['info'] = '請選擇要上傳的圖片'; return $ary; }
以上就是PHP程式碼,原理也很簡單,拿到介面上傳的base64,然後再轉為圖片再儲存。
使用的是thinkphp 3.2,無需資料庫,PHP環境直接執行即可。
php目錄路徑為:
Application\Home\Controller\Base64Controller.class.php
html目錄路徑為:
Application\Home\View\Base64\imagesupload.html
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。