cropper+php+ajax implements uploading avatar

不言
Release: 2023-04-02 19:34:01
Original
3114 people have browsed it

This article mainly introduces the implementation of cropper php ajax to upload avatar, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

  • Front-end code

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>上传头像</title>
<link href="https://cdn.bootcss.com/cropper/3.1.3/cropper.min.css" rel="stylesheet">
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<style type="text/css">
    body{
        text-align: center;
    }
    #user-photo {
        width:300px;
        height:300px;
        margin-top: 10px;
    }
    #photo {
        max-width:100%;
        max-height:350px;
    }
    .img-preview-box {
        text-align: center;
    }
    .img-preview-box > p {
        display: inline-block;;
        margin-right: 10px;
    }
    .img-preview {
        overflow: hidden;
    }
    .img-preview-box .img-preview-lg {
        width: 150px;
        height: 150px;
    }
    .img-preview-box .img-preview-md {
        width: 100px;
        height: 100px;
    }
    .img-preview-box .img-preview-sm {
        width: 50px;
        height: 50px;
        border-radius: 50%;
    }
	
.cropper-view-box, .cropper-face {
    border-radius: 50%;
}
</style>
</head>
<body>
<button class="btn btn-primary" data-target="#changeModal" data-toggle="modal">打开</button><br/>
		<p class="user-photo-box">
			<img id="user-photo" src="">
		</p>
</p>
<p class="modal fade" id="changeModal" tabindex="-1" role="dialog" aria-hidden="true">
<p class="modal-dialog">
    <p class="modal-content">
        <p class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h4 class="modal-title text-primary">
            <i class="fa fa-pencil"></i>
                        更换头像
            </h4>
        </p>
        <p class="modal-body">
            <p class="tip-info text-center">
                未选择图片
            </p>
            <p class="img-container hidden">
                <img src="" alt="" id="photo">
            </p>
            <p class="img-preview-box hidden">
                <hr>
                <span>150*150:</span>
                <p class="img-preview img-preview-lg">
                </p>
                <span>100*100:</span>
                <p class="img-preview img-preview-md">
                </p>
                <span>30*30:</span>
                <p class="img-preview img-preview-sm">
                </p>
            </p>
        </p>
        <p class="modal-footer">
            <label class="btn btn-danger pull-left" for="photoInput">
            <input type="file" class="sr-only" id="photoInput" accept="image/*">
            <span>打开图片</span>
            </label>
            <button class="btn btn-primary disabled" disabled="true" onclick="sendPhoto();">提交</button>
            <button class="btn btn-close" aria-hidden="true" data-dismiss="modal">取消</button>
        </p>
    </p>
</p>
</p>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/cropper/3.1.3/cropper.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">


    var initCropperInModal = function(img, input, modal){
        var $image = img;
        var $inputImage = input;
        var $modal = modal;
        var options = {
            aspectRatio: 1, // 纵横比
            viewMode: 2,
            preview: &#39;.img-preview&#39; // 预览图的class名
        };
        // 模态框隐藏后需要保存的数据对象
        var saveData = {};
        //var URL = window.URL || window.webkitURL;
        var blobURL;
        $modal.on(&#39;show.bs.modal&#39;,function () {
            // 如果打开模态框时没有选择文件就点击“打开图片”按钮
            if(!$inputImage.val()){
                $inputImage.click();
            }
        }).on(&#39;shown.bs.modal&#39;, function () {
            // 重新创建
            $image.cropper( $.extend(options, {
                ready: function () {
                    // 当剪切界面就绪后,恢复数据
                    if(saveData.canvasData){
                        $image.cropper(&#39;setCanvasData&#39;, saveData.canvasData);
                        $image.cropper(&#39;setCropBoxData&#39;, saveData.cropBoxData);
                    }
                }
            }));
        }).on(&#39;hidden.bs.modal&#39;, function () {
            // 保存相关数据
            saveData.cropBoxData = $image.cropper(&#39;getCropBoxData&#39;);
            saveData.canvasData = $image.cropper(&#39;getCanvasData&#39;);
            // 销毁并将图片保存在img标签
            $image.cropper(&#39;destroy&#39;).attr(&#39;src&#39;,blobURL);
        });
        if (URL) {
            $inputImage.change(function() {
                var files = this.files;
                var file;
                if (!$image.data(&#39;cropper&#39;)) {
                    return;
                }
                if (files && files.length) {
                    file = files[0];
                    if (/^image\/\w+$/.test(file.type)) {
    
                        if(blobURL) {
                            URL.revokeObjectURL(blobURL);
                        }
                        blobURL = URL.createObjectURL(file);
    
                        // 重置cropper,将图像替换
                        $image.cropper(&#39;reset&#39;).cropper(&#39;replace&#39;, blobURL);
    
                        // 选择文件后,显示和隐藏相关内容
                        $(&#39;.img-container&#39;).removeClass(&#39;hidden&#39;);
                        $(&#39;.img-preview-box&#39;).removeClass(&#39;hidden&#39;);
                        $(&#39;#changeModal .disabled&#39;).removeAttr(&#39;disabled&#39;).removeClass(&#39;disabled&#39;);
                        $(&#39;#changeModal .tip-info&#39;).addClass(&#39;hidden&#39;);
    
                    } else {
                        window.alert(&#39;请选择一个图像文件!&#39;);
                    }
                }
            });
        } else {
            $inputImage.prop(&#39;disabled&#39;, true).addClass(&#39;disabled&#39;);
        }
    }

    var sendPhoto = function(){
	  
       // 得到PNG格式的dataURL
	
			var photo = $(&#39;#photo&#39;).cropper(&#39;getCroppedCanvas&#39;, {
				width: 300,
				height: 300
			}).toDataURL(&#39;image/png&#39;);

			$.ajax({
				url: &#39;http://localhost/test/upload.php&#39;, // 要上传的地址
				type: &#39;post&#39;,
				data: {
					&#39;imgData&#39;: photo
				},
				dataType: &#39;json&#39;,
				success: function (data) {
					if (data.status == 0) {
						// 将上传的头像的地址填入,为保证不载入缓存加个随机数
						$(&#39;.user-photo&#39;).attr(&#39;src&#39;, &#39;头像地址?t=&#39; + Math.random());
						$(&#39;#changeModal&#39;).modal(&#39;hide&#39;);
					} else {
						alert(data.info);
					}
				}
			});
    }

    $(function(){
        initCropperInModal($(&#39;#photo&#39;),$(&#39;#photoInput&#39;),$(&#39;#changeModal&#39;));
    });
	
</script>
</body>
</html>
Copy after login

  • PHP background processing code Inserting into the database depends on the framework, so I won’t write it down. Later, add thumbnails that automatically cut different sizes

ini_set(&#39;date.timezone&#39;,&#39;Asia/Shanghai&#39;);
/**
 * [将Base64图片转换为本地图片并保存]
 * @E-mial wuliqiang_aa@163.com
 * @TIME   2017-04-07
 * @WEB    http://blog.iinu.com.cn
 * @param  [Base64] $base64_image_content [要保存的Base64]
 * @param  [目录] $path [要保存的路径]
 */
$base64_image_content = $_POST[&#39;imgData&#39;];
$path="./upload";
echo base64_image_content($base64_image_content,$path);
function base64_image_content($base64_image_content,$path){
    //匹配出图片的格式
    if (preg_match(&#39;/^(data:\s*image\/(\w+);base64,)/&#39;, $base64_image_content, $result)){
        $type = $result[2];
        $new_file = $path."/".date(&#39;Ymd&#39;,time())."/";
        if(!file_exists($new_file)){
            //检查是否有该文件夹,如果没有就创建,并给予最高权限
            mkdir($new_file, 0700);
        }
        $new_file = $new_file.time().".{$type}";
        if (file_put_contents($new_file, base64_decode(str_replace($result[1], &#39;&#39;, $base64_image_content)))){
            return &#39;/&#39;.$new_file;
        }else{
            return false;
        }
    }else{
        return false;
    }
}
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone's study , please pay attention to the PHP Chinese website for more related content!

Related recommendations:

php implements socket push technology

Convert objects into JSON strings

The above is the detailed content of cropper+php+ajax implements uploading avatar. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!