标签:pos let func filetype return read span bytes byte
//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); }
标签:pos let func filetype return read span bytes byte
原文地址:http://www.cnblogs.com/toward-the-sun/p/7687916.html