How to effectively implement the front-end compression and upload function

  As the pixels of mobile phones are getting higher and higher, many photos are often several megabytes or even ten megabytes. After uploading, compression on the server side has become less and less able to meet today's needs. For many technicians, they often don't know how to start with such a problem. Then I will explain to you how to compress the image on the front end and upload it to the server.

  Taking uploading a single image as an example, the same is true for multiple images, and one more loop can be nested. The code is implemented as follows:

html:

<!DOCTYPE html>

<html>

<head>

   <meta charset="utf-8" />

   <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

   <meta name="viewport" content="width=device-width, initial-scale=1">

   <title>Image compression upload</title>

   <link href="css/uploadSingleImg.css" rel="stylesheet">

   <link rel="stylesheet" type="text/css" href="css/bootstrap.css">

   <link href="css/style.css" rel="stylesheet"><!--Write your own input style-->

   <script type="text/javascript" src="js/jquery.min.js"></script>

   <script type="text/javascript" src="js/tools.js"></script>

   <script type="text/javascript" src="js/pictureHandle.js"></script>

</head>

<body>

  <form>

 

    <!--File selection input-->

    <h3>File selection:</h3>

    <input class="btn btn-default" type="file" id="upFile" multiple="multiple" />

 

    <h3>Pass to background</h3>

    <input class="btn btn-default" type="button" id="upTo" value="提交"/>

 

    <!--The file base64 to be obtained in the background-->

    <h3>Get base64 file data in the background: (a hidden field)</h3>

    <input id="imgOne" name="imgOne" type="hidden"/>

 

    <!--Preview of selected files before compression-->

    <h3>Pre-compression preview:</h3>

    <img src="" id="preview"/>

    <div id="yulan1"></div>

    <!--Preview after the selected file is compressed-->

    <h3>Preview after compression:</h3>

    <img src="" id="nextview"/>

    <div id="yulan"></div>

  </form>

</body>

</html>

 

Js:

$(function(){

    var _upFile=document.getElementById("upFile");

 

    _upFile.addEventListener("change",function(){

 

    if (_upFile.files.length === 0) {  

        alert("Please select a picture");  

        return; }  

 

    for(var i=0;i<_upFile.files.length;i++){

        var oFile = _upFile.files [i];

 

        if(!new RegExp("(jpg|jpeg|png)+","gi").test(oFile.type)){  

            alert("Photo upload: file type must be JPG, JPEG, PNG");  

            return;  

        }

  

        var reader = new FileReader();  

        reader.onload = function(e) {  

            var base64Img= e.target.result;

            // Preview before compression

            //$("#preview").attr("src",base64Img);  

            var str1 = '<img src="'+base64Img+'">';

            $('#yulan1').append(str1);

            //-- perform resize.  

            var _ir=ImageResizer({  

                    resizeMode:"auto"  

                    ,dataSource:base64Img  

                    ,dataSourceType:"base64"  

                    ,maxWidth:1200 //Maximum width allowed  

                    ,maxHeight:600 //The maximum height allowed.  

                    ,onTmpImgGenerate:function(img){  

 

                    }  

                    ,success:function(resizeImgBase64,canvas){

                        // Preview after compression

                        //$("#nextview").attr("src",resizeImgBase64);

                        var str = '<img src="'+resizeImgBase64+'">';

                        $('#yulan').append(str);

                        //Assign to the hidden field and pass it to the background

                        $('#imgOne').val($('#imgOne').val()+';'+resizeImgBase64.substr(22));

 

                        

 

                    }  

                    ,debug:true  

            });  

 

        };  

        reader.readAsDataURL (oFile);

    }

 

     

  

    },false);  

 

 

    $('#upTo').on('click',function(){

        if (_upFile.files.length === 0) {  

        alert("Please select a picture");  

        return; }

        

        $.ajax({

            url:'server.php',

            type:'POST',

            dataType:'json',

            data:{

                imgOne:$('#imgOne').val()

            },

            success:function(data){

                alert(data.msg);

            }

        });

    });

 

});

 

php processing:

<?php

$img=trim($_POST['imgOne'],';');

$imgarr=explode(';', $img);

foreach($imgarr as $k=>$v){

//decoding

$tmp = base64_decode($v);

//write file

$filename=time().$k.'.jpg';

$path='./upload/';

file_put_contents($path.$filename, $tmp);

}

$res['msg']='Upload successful! ';

echo json_encode($res);

  This method realizes multiple selection of files on the PC side, and the effect of uploading multiple pictures can be selected multiple times on the mobile phone side. Programmers who have understood it now can try it. If there is still something that you don’t understand, you can leave a message below to discuss.

  This article is organized and published by Yixuan Technology, a professional app development company. If you need to reprint, please indicate the original author and source!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324704883&siteId=291194637