<div class="cont"> <ul class="clearfix"> <form enctype="multipart/form-data"> <li> <label>選擇圖片:</label> <input class="file" type="file" id="mBgImg" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg"> <span>640*320</span> </li> </form> </ul> <div class="btn_input"> <input type="button" class="btn cancel" value="取消"> <input type="button" class="btn confirm" id="mBgBtn" value="肯定"> </div> </div>
一、將須要上傳的圖片用<from>處理,代碼如上php
二、js代碼,以下app
$("#mBgBtn").click(function () { //判斷是否有選擇上傳文件 var mBgImg = $("#mBgImg").val(); if (mBgImg == "") { alert("請選擇上傳圖片!"); return; } //判斷上傳文件的後綴名 var strExtension = mBgImg.substr(mBgImg.lastIndexOf('.') + 1); if ( strExtension != 'gif' && strExtension != 'jpeg' && strExtension != 'jpg' && strExtension != 'png' && strExtension != 'svg' ) {alert("請選擇合法圖片上傳!"); return; } //原生JS上傳開始 var xhr; function createXMLHttpRequest(){ if(window.ActiveXObject){ xhr = new ActiveXObject("Microsoft.XMLHTTP"); }else if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); } } var fileObj = document.getElementById("mBgImg").files[0]; var FileController = 'index.php?m=admin_area_mBgImgChg'; var form = new FormData(); form.append("mBgImg", fileObj); createXMLHttpRequest(); xhr.onreadystatechange = handleStateChange; xhr.open("post", FileController, true); xhr.send(form); function handleStateChange(){ if(xhr.readyState == 4){ if (xhr.status == 200 || xhr.status == 0){ var result = xhr.responseText; var ref = result.split('|'); if(ref[0] == -2){ alert(ref[1]); $("#mBgBtn").parents(".popup").hide(); return; }else { alert(ref[1]); return; } } } } //原生JS上傳結束 });