search
HomeBackend DevelopmentPHP Tutorialcropper+php+ajax implements uploading avatar

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 src="/static/imghwm/default1.png"  data-src="" alt="  class="lazy"  id="user-photo" >
		</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="/static/imghwm/default1.png"  data-src="" alt="  class="lazy"   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>

  • 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;
    }
}

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
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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software