標籤:ajax 檔案上傳
項目中經常需要檔案上傳,每次都要重複造輪子,所以決定將檔案上傳做成組件,方便使用。效果
650) this.width=650;" src="https://s2.51cto.com/wyfs02/M02/8D/97/wKiom1iitzjxkUrMAAA0UQkAX5M839.png-wh_500x0-wm_3-wmp_4-s_313052334.png" title="檔案上傳組件.png" alt="wKiom1iitzjxkUrMAAA0UQkAX5M839.png-wh_50" />
自我感覺效果還是可以的,而且使用的代碼也變得十分清晰,前端的html代碼非常簡潔,如下:
<html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><link href = "fileuploader.css" rel="stylesheet"/><script src = "fileuploader.js"></script></head><body><div id = "imageList"></div></body><script>var fileWidget = null;(function(){var imageList = document.getElementById("imageList");fileWidget = new FileWidgt(imageList);fileWidget.newPlaceholder({url:"http://127.0.0.1:8000/App/upload.php"});})();</script></html>
前端代碼只需建立一個FileWidgt類,然後調用newPlaceholder方法即可,所有複雜的操作都封裝到FileWidgt類中。接下來主要分析FileWidgt類。
首先先看一下該組件的結構圖:
650) this.width=650;" src="https://s5.51cto.com/wyfs02/M02/8D/97/wKiom1iiutSzSCLZAAAzcHokTHY323.png-wh_500x0-wm_3-wmp_4-s_2025165928.png" title="上傳組件結構圖.png" alt="wKiom1iiutSzSCLZAAAzcHokTHY323.png-wh_50" />
根據結構圖編寫代碼:
function FileWidgt(ui){this.ui = ui;this.data = "";//記錄選中且已經上傳並返回的結果this.files = [];//用於記錄已選中的檔案,防止重複上傳}FileWidgt.prototype.newPlaceholder = function(s){var fileholder = document.createElement("input");//內部隱藏的輸入框fileholder.setAttribute("type","file");fileholder.setAttribute("name","file");var placeholder = document.createElement("div");//顯示圖片的容器placeholder.setAttribute("class","image-item space");var closeButton = document.createElement(‘div‘);//關閉按鈕closeButton.setAttribute("class","image-close");closeButton.innerHTML = ‘X‘;placeholder.appendChild(fileholder);placeholder.appendChild(closeButton);this.ui.append(placeholder);//顯示圖片的容器加入最外層容器var that = this;closeButton.addEventListener(‘click‘,function(event){event.stopPropagation();event.cancelBubble = true;setTimeout(function(){that.data = that.data.replace(placeholder.getAttribute("image-data"),"");//data中去除該關閉的圖片結果that.data = that.data.replace(",,",",");if(that.data.length > 0 && that.data.charAt(0) == ","){that.data = that.data.substring(1);}else if(that.data.length > 0 && that.data.charAt(that.data.length - 1) == ","){that.data = that.data.substring(0,that.data.length - 1);}that.ui.removeChild(placeholder);//去除關閉的顯示容器},0);},false);placeholder.addEventListener("click",fileholder.onclick,false);//點擊調用檔案上傳fileholder.addEventListener("change",function(e){//選中檔案後上傳圖片if(that.files.join(",").indexOf(fileholder.value) == -1){var formData = new FormData();formData.append("file",fileholder.files[0]);var xhr = null;if(window.ActiveXObject){xhr = new ActiveXObject("Microsoft.XMLHTTP");}else{xhr = new XMLHttpRequest();}xhr.open(s.method||‘POST‘,s.url,true);xhr.onreadystatechange = function(){//Ajax檔案上傳返回if(xhr.readyState == 4 && xhr.status == 200){var filename = JSON.parse(xhr.responseText).filename;placeholder.style.backgroundImage = ‘url(‘+filename+‘)‘;//替換當前添加圖片為上傳檔案的圖片if(placeholder.getAttribute("image-data") == undefined ||placeholder.getAttribute("image-data") == ""){placeholder.classList.remove(‘space‘);placeholder.removeEventListener("click",fileholder.onclick,false);placeholder.removeChild(fileholder);that.newPlaceholder(s);//建立一個添加的表徵圖}//給data值添加當前上傳的檔案地址if(that.data == ""){that.data = filename;placeholder.setAttribute("image-data",filename);}else{that.data += "," + filename;placeholder.setAttribute("image-data",filename);}}}xhr.send(formData);}},false);}FileWidgt.prototype.getData = function(){return this.data;}
樣式代碼:
.image-item {width: 65px;height: 65px;background-image: url(img/iconfont-tianjia.png);background-size: 100% 100%;display: inline-block;position: relative;border-radius: 5px;margin-right: 10px;margin-bottom: 10px;border: solid 1px #e8e8e8;}.image-item input[type="file"] {position: absolute;left: 0px;top: 0px;width: 100%;height: 100%;opacity: 0;cursor: pointer;z-index: 0;}.image-item .image-close {position: absolute;display: inline-block;right: -6px;top: -6px;width: 20px;height: 20px;text-align: center;line-height: 20px;border-radius: 12px;background-color: #FF5053;color: #f3f3f3;border: solid 1px #FF5053;font-size: 9px;font-weight: 200;z-index: 1;}.image-item.space .image-close {display: none;}
後台代碼:
<?phpheader("Access-Control-Allow-Origin:*");file_put_contents("log.log",$_FILES[‘file‘][‘name‘]);move_uploaded_file($_FILES[‘file‘][‘tmp_name‘],‘upload/‘.$_FILES[‘file‘][‘name‘]);echo json_encode(array("filename"=>‘http://‘.$_SERVER["REMOTE_ADDR"].‘:‘.$_SERVER["SERVER_PORT"].‘/App/upload/‘.$_FILES[‘file‘][‘name‘]));?>
說明:後台代碼對中文名稱檔案沒有做操作,大家可以用自己喜歡的語言做後台代碼。
本文出自 “走一停二回頭看三” 部落格,請務必保留此出處http://janwool.blog.51cto.com/5694960/1897696
Ajax檔案上傳組件