標籤:mat process view ons 圖片下載 var 重設 username func
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;
}
input 單圖上傳