HTML5 文件域+FileReader 分段读取文件并上传到服务器

2019-01-28 13:17:23于海丽

后台代码同上

3.分段读取文件为二进制数组 ,并使用ajax上传到服务器

 使用二进制数组传递的方式,效率特别低,最终文件还与原始大小有些偏差

HTML内容同上

JS:

/* * 分段读取文件为二进制数组 ,并使用ajax上传到服务器 * 使用二进制数组传递的方式,效率特别低,最终文件还与原始大小有些偏差 */ var fileBox = document.getElementById('file'); var reader = new FileReader(); //读取操作对象 var step = 1024 * 1024; //每次读取文件大小 var cuLoaded = 0; //当前已经读取总数 var file = null; //当前读取的文件对象 var enableRead = true;//标识是否可以读取文件 fileBox.onchange = function () { //获取文件对象 if (file == null) //如果赋值多次会有丢失数据的可能 file = this.files[0]; var total = file.size; console.info("文件大小:" + file.size); var startTime = new Date(); //读取一段成功 reader.onload = function (e) { //处理读取的结果 var result = reader.result; var loaded = e.loaded; if (enableRead == false) return false; //将分段数据上传到服务器 uploadFile(result, cuLoaded, function () { console.info('loaded:' + cuLoaded + '----current:' + loaded); //如果没有读完,继续 cuLoaded += loaded; if (cuLoaded < total) { readBlob(cuLoaded); } else { console.log('总共用时:' + (new Date().getTime() - startTime.getTime()) / 1000); cuLoaded = total; } //显示结果进度 var percent = (cuLoaded / total) * 100; document.getElementById('Status').innerText = percent; document.getElementById('progressOne').value = percent; }); } //开始读取 readBlob(0); //关键代码上传到服务器 function uploadFile(result, startIndex, onSuccess) { var array = new Int8Array(result); console.info(array.byteLength); //提交到服务器 var fd = new FormData(); fd.append('file', array); fd.append('filename', file.name); fd.append('loaded', startIndex); var xhr = new XMLHttpRequest(); xhr.open('post', '../ashx/upload3.ashx', true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { // console.info(xhr.responseText); if (onSuccess) onSuccess(); } else if (xhr.status == 500) { console.info('服务器出错'); reader.abort(); } } //开始发送 xhr.send(fd); } } //指定开始位置,分块读取文件 function readBlob(start) { //指定开始位置和结束位置读取文件 var blob = file.slice(start, start + step); reader.readAsArrayBuffer(blob); } //中止 function stop() { //中止读取操作 console.info('中止,cuLoaded:' + cuLoaded); enableRead = false; reader.abort(); } //继续 function containue() { console.info('继续,cuLoaded:' + cuLoaded); enableRead = true; readBlob(cuLoaded); }