JS 代码
- // 选择图片
- $(".change-pic-btn").change(function(event){
- var self=this;
- var img = event.target.files[0];
- // 判断是否图片
- if(!img){
- return ;
- }
- // 判断是否有文件对象
- if(!(img.type.indexOf('image')==0 && img.type && /\.(?:jpg|PNG|gif|jpeg)$/.test(img.name)) ){
- imgThisObj.find(".upload-pic-lay").html('<section class="input-tips-box red"> 图片只能是 jpg,gif,png,jpeg</section>');
- return ;
- }
- var reader = new FileReader();
- reader.readAsDataURL(img);
- reader.onload = function(){
- //this.result 就是 base64 格式
- imgThisObj.find(".upload-pic-lay").HTML('<img src="'+this.result+'"/>');
- };
- });
PHP 代码
- public function savebase64ToImg(){
- if(IS_AJAX){
- $base64 = $_POST["file"];
- $path = "./Uploads/Answer/";
- $name = "test_{$userId}_".time();
- $file = base64SaveImg($base64,$path,$name);
- $this->ajaxReturn($file);
- }
- }
- /**
- * 保存 base64 编码图片
- *@param string $base64
- *@param string $path
- *@param string $fileName
- *@return string
- */
- function base64SaveImg($base64, $path, $fileName) {
- if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result)) {
- $type = $result[2];
- $new_file = $path . "/" . $fileName . ".{$type}";
- // 检测目录是否存在并创建目录
- if (!file_exists($path)) {
- $reval = false;
- @umask(0);
- preg_match_all('/([^\/]*)\/?/i', $path, $atmp);
- $base = ($atmp[0][0] == '/') ? '/' : '';
- foreach ($atmp[1] AS $val) {
- if ('' != $val) {
- $base .= $val;
- if ('..' == $val || '.' == $val) {
- $base .= '/';
- continue;
- }
- } else {
- continue;
- }
- $base .= '/';
- if (!file_exists($base)) {
- if (@mkdir(rtrim($base, '/'), 0777)) {
- @chmod($base, 0777);
- $reval = true;
- }
- }
- }
- }
- if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64)))) {
- return $new_file;
- } else {
- return null;
- }
- } else {
- return null;
- }
- }
来源: http://www.jianshu.com/p/8cef14f444d6