input 單圖上傳

來源:互聯網
上載者:User

標籤: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 單圖上傳

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.