(1)<input type="file">標籤 (點擊閱讀參考資料)
(2)利用addEventListener()事件監聽<input type='file'>改變(點擊閱讀參考資料)
(3)利用HTML5FileReader()中的.readAsDataURL()方法將圖片url轉爲Base64位碼(點擊閱讀參考資料)
(4)FileReader.onload()方法(點擊參考資料)html
ES5:
源碼:app
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>input file圖片上傳</title> </head> <body> <input type="file" accept="image/*" id="file" value=""/> <div id="uploadImg" style="width: 500px; height: 500px;"> </div> </body> <script> var oUploadImg = document.querySelector("#uploadImg") //獲取uploaImg節點, oFile = document.querySelector("#file"); //獲取input file節點 console.log(oUploadImg); console.log(oFile); console.log(oFile.files); oFile.addEventListener('change',function(){ // console.log(oUploadImg); // console.log(oFile); console.log(this); //this指針指向input console.log(this.files); var file = this.files[0]; console.log(file.type); console.log(file.type.indexOf("image"));//輸出0的時候成立,-1的時候不成立 if(file.type.indexOf("image")==0){ var reader = new FileReader(); //建立FileReader對象實例reader reader.readAsDataURL(file); //將圖片url轉換爲base64碼 reader.onload = function(e){ var newUrl = this.result; console.log(newUrl); oUploadImg.style.backgroundImage = 'url('+newUrl+')'; } console.log(reader.result); console.log(reader); console.log(reader); }; }) </script> </html>
(1)formData()表單提交方法(點擊閱讀材料)dom
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>input file圖片上傳</title> </head> <body> <input type="file" accept="image/*" id="file" value="" multiple/> <div id="uploadImg" style="width: 500px; height: 500px;"> </div> </body> <script> var oUploadImg = document.querySelector("#uploadImg") //獲取uploaImg節點, oFile = document.querySelector("#file"); //獲取input file節點 console.log(oUploadImg); console.log(oFile); console.log(oFile.files); oFile.addEventListener('change',function(){ // console.log(oUploadImg); // console.log(oFile); console.log(this); //this指針指向input console.log(this.files); //創立FormData對象 var formData = new FormData(); //實例化一個formData對象 formData.append =("file",this.files); //this.files對象轉換爲字符串 console.log(formData); console.log(formData); }) </script> </html>