//1,第一步讀取用戶選中的文件 <input type="file" accept="image/*" onchange = "selectedFile()"/> function selectedFile(){ var oFile = event.target.files[0]; var fileReader = new FileReader(); fileReader.onload = function(){ var base64URL = this.result ; var blob = convertBase64UrlToBlob(base64URL,'image/jpeg'); uploadImage(blob); } fileReader.readAsDataURL(oFile) } //2,第二步將base64圖片轉換爲Blob對象 function convertBase64UrlToBlob(urlData, filetype){ //去掉url的頭,並轉換爲byte var bytes = window.atob(urlData.split(',')[1]); //處理異常,將ascii碼小於0的轉換爲大於0 var ab = new ArrayBuffer(bytes.length); var ia = new Int8Array(ab); var i; for (i = 0; i < bytes.length; i++) { ia[i] = bytes.charCodeAt(i); } return new Blob([ab], {type : filetype}); } //3,第三步使用formData上傳數據 function uploadImage(blob){ var formData = new FormData(); formData.append('userProfile',blob); var xhr = new XMLHttpRequest(); // xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // 將參數解析成傳統form的方式上傳 xhr.open('post', '/upload.php',true);
xhr.onload = fn();//上傳成功事件監聽
xhr.onerror = fn(); //上傳失敗事件監聽
xhr.send(formData); }
var change = function(){ var file = event.target.files[0]; var fileReader = new FileReader(); fileReader.onload = function(){ var result = this.result; var blob = new Blob([result],{type:file.type}); var formData = new FormData(); formData.append('userAvatar',blob,file.name);
//添加其餘表單字段 formData.append('username',document.getElementById("uname").value) formData.append('pwd',document.getElementById("upwd").value); $.ajax({ type:"post", url:"http://localhost:3000/uploads", async:true, processData:false, contentType:false, data:formData, timeout:6000, success:function (data) { console.log('upload success') }, error:function (xhr,text) { if(text === 'timeout'){ xhr.abort(); } } }); } fileReader.readAsArrayBuffer(file); }