


One trick to achieve asynchronous upload of compressed images using JS
This article mainly introduces in detail the JS implementation of asynchronous uploading of compressed images and immediate display of images. It has certain reference value. Interested friends can refer to it.
Abstract: Use iframe to Processing asynchronous uploading of images is more or less backward in this era! Isn’t it possible to upload images asynchronously using AJAX and JS alone?
Thank you think2011 for this brother’s JS library: github.com/think2011/LocalResizeIMG
Look at the calling page first:
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no"> <script type="text/javascript" src="./js/lrz.mobile.min.js"></script> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> </head> <body class="upload"> <form id="form"> <p id="img_show"></p> <p id="upload"> <p id="img_file"><input type="file" accept="image/*" ><p class="btn">选择图片</p></p> </p> <input type="submit" class="tijiao" value="提交"> </form> </body> <script type="text/javascript"> var img; $("input:file").change(function (){ //console.log(this.files[0]); lrz(this.files[0],{width:640,quality:0.9},function(rst){ img = rst.base64; var html = []; var show_img = new Image(); show_img.src = rst.base64; $("#img_show").html("<p class='upimg'></p>"); $(".upimg").html(show_img); }); }); $("#form").submit(function (){ var phone = $("input[name='phone']").val(); var month = $("input[name='month']").val(); $.post("upload.php",{img:img,phone:phone,month:month},function(data){ img = null; alert(data.msg); },'json'); return false; }); </script> </html>
1. First you need to load Enter the JS class library:
2. Then write the form
3. Prepare the JS for processing images and asynchronous submission of images.
<script type="text/javascript"> var img; $("input:file").change(function (){ //console.log(this.files[0]); lrz(this.files[0],{width:640,quality:0.9},function(rst){ img = rst.base64; var html = []; var show_img = new Image(); show_img.src = rst.base64; $("#img_show").html("<p class='upimg'></p>"); $(".upimg").html(show_img); }); }); $("#form").submit(function (){ var phone = $("input[name='phone']").val(); var month = $("input[name='month']").val(); $.post("upload.php",{img:img},function(data){ img = null; alert(data.msg); },'json'); return false; }); </script>
As can be seen from the code, this JS library converts the image into code, then stores it in a variable, and then uses asynchronous POST to the server for processing.
It seems there is nothing special about it, indeed there is nothing special about it...
Background processing program PHP:
function error($msg=''){ $return = array('msg'=>$msg); echo json_encode($return); exit(); } function main(){ if(!$_POST['img']){ error('请上传图片!'); } $img = $_POST['img']; $path = './upload/'; $type_limit = array('jpg','jpeg','png'); if(preg_match('/data:\s*image\/(\w+);base64,/iu',$img,$tmp)){ if(!in_array($tmp[1],$type_limit)){ error('图片格式不正确,只支持jpg,jpeg,png!'); } }else{ error('抱歉!上传失败,请重新再试!'); } $img = str_replace(' ','+',$img); $img = str_replace($tmp[0], '', $img); $img = base64_decode($img); $file = $path.time().'.'.$tmp[1]; if(!file_put_contents($file,$img)){ error('上传图片失败!'); }else{ error('恭喜您!上传成功!'); } } main();
Above If there are any errors in the code, please point them out.
As for the appeal code, as you can see, after the BASE64-encrypted image code comes to the backend through JS asynchronous POST, we need to restore the code. However, the JS library will have some tags when encrypted, so these things that are not originally images need to be processed before restoration.
$img = str_replace(' ','+',$img); $img = str_replace($tmp[0], '', $img); $img = base64_decode($img);
Finally, insert the code into the file, set the corresponding file name and extension, and the image will be successfully uploaded to the server.
Note:
The front-end and back-end including JS encoding must be consistent. It is recommended to UTF-8
If the image restoration will not come, then it must be There is a data problem. Print the image code from POST and take a look.
Students who need to learn js please pay attention to php Chinese website js video tutorial, many js online video tutorials can be watched for free!
The above is the detailed content of One trick to achieve asynchronous upload of compressed images using JS. 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

AI Hentai Generator
Generate AI Hentai for free.

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



1. How does MeituXiuXiu compress the image size? Meituxiuxiu tutorial on changing photo size kb! 1. Enter the Meitu Xiu Xiu app and click on Picture Beautification. 2. Go to the recent projects interface and select the pictures that need to be compressed. 3. Enter the picture interface and click the edit option below. 4. Jump to the editing interface and select the image format. 5. After the selection is successful, click the size in the middle of the picture to enter. 6. Enter the modification size interface, adjust the size of the image, and click Save after the adjustment is completed. 7. Return to the picture interface, find the check icon in the lower right corner and click it. 8. Finally, in the compressed image interface, click Save and the image will be compressed.

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese
