cropper+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 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: '.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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
