我們在開發(fā)系統(tǒng)時(shí),處理圖片上傳是不可避免的,例如使用thinkphp的肯定很熟悉import("@.ORG.UploadFile");的上傳方式,今天我們來講一個使用html5 base64上傳圖片的方法。
主要是用到html5 FileReader的接口,既然是html5的,所支持的瀏覽器我就不多說啦
可以大概的講一下思路,其實(shí)也挺簡單。選擇了圖片之后,js會先把已選的圖片轉(zhuǎn)化為base64格式,然后通過ajax上傳到服務(wù)器端,服務(wù)器端再轉(zhuǎn)化為圖片,進(jìn)行儲存的一個過程。
咱們先看看前端的代碼。
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;
//打印到控制臺,按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('上傳超時(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'] = '請選擇要上傳的圖片';
return $ary;
}
以上就是PHP代碼,原理也很簡單,拿到接口上傳的base64,然后再轉(zhuǎn)為圖片再儲存。
使用的是thinkphp 3.2,無需數(shù)據(jù)庫,PHP環(huán)境直接運(yùn)行即可。
php目錄路徑為:
Application\Home\Controller\Base64Controller.class.php
html目錄路徑為:
Application\Home\View\Base64\imagesupload.html
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- PHP保存Base64圖片base64_decode的問題整理
- php curl簡單采集圖片生成base64編碼(并附curl函數(shù)參數(shù)說明)
- PHP實(shí)現(xiàn)將base64編碼字符串轉(zhuǎn)換成圖片示例
- php讀取和保存base64編碼的圖片內(nèi)容
- php實(shí)現(xiàn)base64圖片上傳方式實(shí)例代碼
- php解析base64數(shù)據(jù)生成圖片的方法
- php實(shí)現(xiàn)將base64格式圖片保存在指定目錄的方法
- 利用PHP將圖片轉(zhuǎn)換成base64編碼的實(shí)現(xiàn)方法
- php中base64_decode與base64_encode加密解密函數(shù)實(shí)例
- PHP 實(shí)現(xiàn)base64編碼文件上傳出現(xiàn)問題詳解