用H5上传文件
//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); }
一种更简便的H5上传方式
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); }