Use ajax to upload pictures, support instant browsing of pictures, support js picture compression and upload to the server
Ajax upload mainly uses var reader = new FileReader() This method
js image compression is mainly carried out using canvas
Source code:
/** * js uses form to upload images, supports local preview of selected images, and supports carrying custom parameters * @param {string} params.previewImgId preview image control id, you can preview the uploaded image * @param {string} params.url submit upload url * @param {function} params.success callback function of upload interface * @param {boolean} params.params There are several other parameters submitted when uploading, and the system will pass the other parameters filtered by the three parameters previewImgId url success to the server Example of use: <img src="" id="yulan"> <div onclick="shangchuan()">上传</div> function shangchuan(){ jsUploadImage({"diyparam":"1111","diyparam1":"222","previewImgId":"yulan","url":"user.php?act=photosave","success":function(data){ console.log(data); }}) }; */ function jsUploadImage(params){ //Initialization data params.previewImgId = params.previewImgId || ""; params.url = params.url || ""; params.success = params.success || ""; //Create a file upload control if(document.getElementById("imgFile")==null){ var inputEle=document.createElement("input"); //创建input inputEle.id="imgFile"; inputEle.type="file"; inputEle.accept="image/png,image/jpeg,image/jpeg,DCIM/*;capture=camera"; inputEle.style="display:none;"; inputEle.onchange = function(){ showPhoto() }; inputEle.multiple = false; document.body.appendChild(inputEle); } var imgFile = document.getElementById("imgFile"); imgFile.click(); // Preview image after selecting the file function showPhoto(){ // file object var file = document.getElementById("imgFile").files[0]; / / Read the suffix to determine whether the file is allowed var fileSuffix = file.name.substring(file.name.length-4); var allowFile = ".jpg|.png|.gif"; if(allowFile.indexOf(fileSuffix.toLowerCase())==-1) { alert("Please use "+allowFile+" suffix file"); return false; } //If the id of the display control is passed, display the local preview var reader = new FileReader() reader.readAsDataURL(file); reader.onload = function(e){ var imgBase64Data = e.target.result; // show preview if("" != params.previewImgId) document.getElementById(params.previewImgId).src = imgBase64Data; //If you don't compress and upload directly //savePhoto(imgBase64Data) //Reduce the image and upload it again compressPhoto(imgBase64Data,1000,1000,function(imgBase64DataBack){ //Submit service to save data savePhoto(imgBase64DataBack) }); } } //submit data function savePhoto(base64Data){ var formData = new FormData(); //add other parameters for(var key in params){ if(key!="previewImgId" && key!="url" && key!="success" ){ formData.append(key, params[key]); } } //Add file parameters to use base64 formData.append("imgFile",encodeURIComponent(base64Data)); //Add the file parameter file control to upload, but this test does not support image compression, so the mobile phone does not use this method //formData.append('imgFile', file); //ajax upload $.ajax({ url:params.url, type: 'POST', cache: false, dataType:"json", data: formData, processData: false, contentType: false }).done(function(res) { if(params.success!=""){ params.success(res); } }).fail(function(res) { alert("Upload failed"); }); } } /** * js uses canvas to compress images * @param {string} imgBase64Data image base64 data * @param {string} maxWidth max height * @param {function} maxHeight maximum width * @param {boolean} fun callback function, the parameter is the processed image data Example of use: compressPhoto(imgBase64Data,maxWidth,maxHeight,function(imgBase64Data){ //Processing after returning the image data }) */ function compressPhoto(imgBase64Data,maxWidth,maxHeight,fun){ var img = new Image(); // Canvas needed to zoom the image var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); // After the base64 address image is loaded img.onload = function () { // original image size var originWidth = this.width; var originHeight = this.height; // target size var targetWidth = originWidth, targetHeight = originHeight; // The image size exceeds the limit of 400x400 if (originWidth > maxWidth || originHeight > maxHeight) { if (originWidth / originHeight > maxWidth / maxHeight) { // wider, limit the size according to the width targetWidth = maxWidth; targetHeight = Math.round(maxWidth * (originHeight / originWidth)); } else { targetHeight = maxHeight; targetWidth = Math.round(maxHeight * (originWidth / originHeight)); } } // canvas zooms the image canvas.width = targetWidth; canvas.height = targetHeight; // clear the canvas context.clearRect(0, 0, targetWidth, targetHeight); // Picture compression context.drawImage(img, 0, 0, targetWidth, targetHeight); var base=canvas.toDataURL("image/jpeg",0.7);//canvas is converted to base64 fun(base);//return processing }; img.src = imgBase64Data; }
Example of use:
<img src="" id="yulan"> <div onclick="shangchuan()">上传</div> <script type="text/javascript"> function shangchuan(){ jsUploadImage({"diyparam":"1111","diyparam1":"222","previewImgId":"yulan","url":"user.php?act=photosave","success":function(data){ console.log(data); }}) }; </script>
来源:jsfun.cn
http://www.jsfun.cn/#codecollect