Home Backend Development PHP Tutorial cropper+php+ajax implements uploading avatar

cropper+php+ajax implements uploading avatar

Jul 07, 2018 pm 01:48 PM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles