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: '.img-preview' // 预览图的class名 }; // 模态框隐藏后需要保存的数据对象 var saveData = {}; //var URL = window.URL || window.webkitURL; var blobURL; $modal.on('show.bs.modal',function () { // 如果打开模态框时没有选择文件就点击“打开图片”按钮 if(!$inputImage.val()){ $inputImage.click(); } }).on('shown.bs.modal', function () { // 重新创建 $image.cropper( $.extend(options, { ready: function () { // 当剪切界面就绪后,恢复数据 if(saveData.canvasData){ $image.cropper('setCanvasData', saveData.canvasData); $image.cropper('setCropBoxData', saveData.cropBoxData); } } })); }).on('hidden.bs.modal', function () { // 保存相关数据 saveData.cropBoxData = $image.cropper('getCropBoxData'); saveData.canvasData = $image.cropper('getCanvasData'); // 销毁并将图片保存在img标签 $image.cropper('destroy').attr('src',blobURL); }); if (URL) { $inputImage.change(function() { var files = this.files; var file; if (!$image.data('cropper')) { 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('reset').cropper('replace', blobURL); // 选择文件后,显示和隐藏相关内容 $('.img-container').removeClass('hidden'); $('.img-preview-box').removeClass('hidden'); $('#changeModal .disabled').removeAttr('disabled').removeClass('disabled'); $('#changeModal .tip-info').addClass('hidden'); } else { window.alert('请选择一个图像文件!'); } } }); } else { $inputImage.prop('disabled', true).addClass('disabled'); } } var sendPhoto = function(){ // 得到PNG格式的dataURL var photo = $('#photo').cropper('getCroppedCanvas', { width: 300, height: 300 }).toDataURL('image/png'); $.ajax({ url: 'http://localhost/test/upload.php', // 要上传的地址 type: 'post', data: { 'imgData': photo }, dataType: 'json', success: function (data) { if (data.status == 0) { // 将上传的头像的地址填入,为保证不载入缓存加个随机数 $('.user-photo').attr('src', '头像地址?t=' + Math.random()); $('#changeModal').modal('hide'); } else { alert(data.info); } } }); } $(function(){ initCropperInModal($('#photo'),$('#photoInput'),$('#changeModal')); }); </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('date.timezone','Asia/Shanghai'); /** * [将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['imgData']; $path="./upload"; echo base64_image_content($base64_image_content,$path); function base64_image_content($base64_image_content,$path){ //匹配出图片的格式 if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){ $type = $result[2]; $new_file = $path."/".date('Ymd',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], '', $base64_image_content)))){ return '/'.$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!

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

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

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.

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

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.

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

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.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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
Powerful PHP integrated development environment

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
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
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
