input 单图上传

html

  <input type="file" name="identity_card_front" onchange="previewImage(this,0)" style="display: none;">

js

  function previewImage(file){

//判断上传图片的格式及大小start
photoExt=file.value.substr(file.value.lastIndexOf(".")).toLowerCase();//获得文件后缀名
console.log(photoExt)
if(photoExt != '.jpg' && photoExt !='.jpeg' && photoExt!= '.png'){
alertShow("请上传正确格式的照片!");
return;
}
var fileSize = 0;
var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
if (isIE && !file.files) {
var filePath = obj.value;
var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
var file = fileSystem.GetFile (filePath);
fileSize = file.Size;
}else {
fileSize = file.files[0].size;
}
fileSize=Math.round(fileSize/1024*100)/100; //单位为KB
if(fileSize>=2048){
alertShow("照片最大尺寸为2M,请重新上传!");
return false;
}
//判断上传图片的格式及大小end

var div = file.previousSibling.previousSibling;//img元素外box元素

if (file.files && file.files[0]){
var name ;//文件名称

div.innerHTML ='<img>';//图片上传完后不可再次点击
var img = div.firstChild;//此为img元素
img.onload = function(){//图片下载完毕时
   //自定的最大高、宽 和 原图的宽高
   var rect = definedSize(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
          img.width = rect.width;
     img.height = rect.height;
     img.style.marginTop = rect.top+10+'px';
}

var data=new FormData();

data.append('file',file.files[0]);
data.append('username',name);
data.append('type',papersType)

$.ajax({
type:'post',
url:rootPath+'   ',
dataType:'json',
contentType: false,
processData: false,
data:data,
success:function(res){
img.src =  res.data.imageUrl

}
})
}

  }

//重置图片大小
function definedSize( maxWidth, maxHeight, width, height ){
var param = {top:0, left:0, width:width, height:height};
if( width>maxWidth || height>maxHeight ){//如果宽高大于最大宽高
rateWidth = width / maxWidth;//宽了几倍
rateHeight = height / maxHeight;//高了几倍

if( rateWidth > rateHeight ){
param.width = maxWidth;
param.height = Math.round(height / rateWidth);
}else{
param.width = Math.round(width / rateHeight);
param.height = maxHeight;
}
}
param.left = Math.round((maxWidth - param.width) / 2);
param.top = Math.round((maxHeight - param.height) / 2);
return param;
}

posted @ 2017-07-11 18:43  adolfvicto  阅读(613)  评论(0编辑  收藏  举报