PHP實(shí)現(xiàn)本地圖片轉(zhuǎn)base64格式并上傳
我們?cè)陂_發(fā)系統(tǒng)時(shí),處理圖片上傳是不可避免的,例如使用thinkphp的肯定很熟悉import('@.ORG.UploadFile');的上傳方式,今天我們來講一個(gè)使用html5 base64上傳圖片的方法。
主要是用到html5 FileReader的接口,既然是html5的,所支持的瀏覽器我就不多說啦
可以大概的講一下思路,其實(shí)也挺簡(jiǎn)單。選擇了圖片之后,js會(huì)先把已選的圖片轉(zhuǎn)化為base64格式,然后通過ajax上傳到服務(wù)器端,服務(wù)器端再轉(zhuǎn)化為圖片,進(jìn)行儲(chǔ)存的一個(gè)過程。
咱們先看看前端的代碼。
html部分
<input type='file' id='imagesfile'>
js部分
$('#imagesfile').change(function (){ var file = this.files[0]; //用size屬性判斷文件大小不能超過5M ,前端直接判斷的好處,免去服務(wù)器的壓力。 if( file.size > 5*1024*1024 ){ alert( '你上傳的文件太大了!' ) } //好東西來了 var reader=new FileReader(); reader.onload = function(){ // 通過 reader.result 來訪問生成的 base64 DataURL var base64 = reader.result; //打印到控制臺(tái),按F12查看 console.log(base64); //上傳圖片 base64_uploading(base64); } reader.readAsDataURL(file);});//AJAX上傳base64function 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(’上傳超時(shí)啦,再試試’); } });}
其實(shí)前端的代碼也并不復(fù)雜,主要是使用了new FileReader();的接口來轉(zhuǎn)化圖片,new FileReader();還有其他的接口,想了解更多的接口使用的童鞋,自行谷歌搜索new FileReader();。
接下來,那就是服務(wù)器端的代碼了,上面的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, 0,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’] = ’請(qǐng)選擇要上傳的圖片’; return $ary; }
以上就是PHP代碼,原理也很簡(jiǎn)單,拿到接口上傳的base64,然后再轉(zhuǎn)為圖片再儲(chǔ)存。
使用的是thinkphp 3.2,無需數(shù)據(jù)庫,PHP環(huán)境直接運(yùn)行即可。
php目錄路徑為:
ApplicationHomeControllerBase64Controller.class.php
html目錄路徑為:
ApplicationHomeViewBase64imagesupload.html
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. JAMon(Java Application Monitor)備忘記2. SpringBoot+TestNG單元測(cè)試的實(shí)現(xiàn)3. Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法4. VMware中如何安裝Ubuntu5. Springboot 全局日期格式化處理的實(shí)現(xiàn)6. python 浮點(diǎn)數(shù)四舍五入需要注意的地方7. Docker容器如何更新打包并上傳到阿里云8. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法9. idea配置jdk的操作方法10. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問題
