上传头像插件megapix-image.js

2017-09-14  本文已影响0人  恒不动

github下载地址点我

demo

<input type="file" name="imgFile" id="topFile" accept="image/gif,image/jpeg,image/jpg,image/png">
<script type="text/javascript">
$(function() {
     //检测手机系统
    var ua = navigator.userAgent.toLowerCase(); 
    if (/android/.test(ua)) { 
            $("#topFile").attr("capture", "camera");    
    }
    $("#topFile").change(function() {
        if (this.files && this.files[0]) {
            var file = this.files[0];
            var mpImg = new MegaPixImage(file);
            var resImg = document.getElementById('topPhoto');
            resImg.onload=function(){
                if(resImg.src.indexOf("data:")==0){
                   var imgBase64=resImg.src;
                   sumitImageFile(imgBase64);
                }
            };
            mpImg.render(resImg, { maxWidth: 500, maxHeight: 500, quality: 0.5 });
        }
    });
});
/**
 * ajax上传头像
 */
function sumitImageFile(base64Codes){  
    var formData = new FormData();
    formData.append("photofile",convertBase64UrlToBlob(base64Codes));
    $.ajax({  
        url :  "",  
        type : "POST",  
        data : formData,  
        dataType:"json",  
        processData : false,
        contentType : false,
        success:function(data){  
            if(!data.success){
                  alert(data.errInfo);
            }
        }
    });  
}  
  
/**  
 * 将以base64的图片url数据转换为Blob  
 * @param urlData  
 */  
function convertBase64UrlToBlob(urlData){  
    //去掉url的头,并转换为byte
    var bytes=window.atob(urlData.split(',')[1]);  
    //处理异常,将ascii码小于0的转换为大于0  
    var ab = new ArrayBuffer(bytes.length);  
    var ia = new Uint8Array(ab);  
    for (var i = 0; i < bytes.length; i++) {  
        ia[i] = bytes.charCodeAt(i);  
    }  
    return new Blob( [ab] , {type : 'image/png'});  
}  
</script>


后台代码
public String uploadImg(@RequestParam(value="photofile",required=false) MultipartFile file){
     //上传file
}
上一篇下一篇

猜你喜欢

热点阅读