這篇文章主要介紹html5中文件域+FileReader分段如何讀取文件并上傳到服務(wù)器,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!
創(chuàng)新互聯(lián)專業(yè)IDC數(shù)據(jù)服務(wù)器托管提供商,專業(yè)提供成都服務(wù)器托管,服務(wù)器租用,四川服務(wù)器托管,四川服務(wù)器托管,成都多線服務(wù)器托管等服務(wù)器托管服務(wù)。
1.簡單分段讀取文件為Blob,ajax上傳到服務(wù)器
分段讀取文件:
JS:
/* * 分段讀取文件為blob ,并使用ajax上傳到服務(wù)器 * 分段上傳exe文件會拋出異常 */ var fileBox = document.getElementById('file'); file.onchange = function () { //獲取文件對象 var file = this.files[0]; var reader = new FileReader(); var step = 1024 * 1024; var total = file.size; var cuLoaded = 0; console.info("文件大小:" + file.size); var startTime = new Date(); //讀取一段成功 reader.onload = function (e) { //處理讀取的結(jié)果 var loaded = e.loaded; //將分段數(shù)據(jù)上傳到服務(wù)器 uploadFile(reader.result, cuLoaded, function () { console.info('loaded:' + cuLoaded + 'current:' + loaded); //如果沒有讀完,繼續(xù) cuLoaded += loaded; if (cuLoaded < total) { readBlob(cuLoaded); } else { console.log('總共用時:' + (new Date().getTime() - startTime.getTime()) / 1000); cuLoaded = total; } }); } //指定開始位置,分塊讀取文件 function readBlob(start) { //指定開始位置和結(jié)束位置讀取文件 //console.info('start:' + start); var blob = file.slice(start, start + step); reader.readAsArrayBuffer(blob); } //開始讀取 readBlob(0); //關(guān)鍵代碼上傳到服務(wù)器 function uploadFile(result, startIndex, onSuccess) { var blob = new Blob([result]); //提交到服務(wù)器 var fd = new FormData(); fd.append('file', blob); fd.append('filename', file.name); fd.append('loaded', startIndex); var xhr = new XMLHttpRequest(); xhr.open('post', '../ashx/upload2.ashx', true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { // var data = eval('(' + xhr.responseText + ')'); console.info(xhr.responseText); if (onSuccess) onSuccess(); } } //開始發(fā)送 xhr.send(fd); } }
后臺代碼:
////// upload2 的摘要說明 /// public class upload2 : IHttpHandler { LogHelper.LogHelper _log = new LogHelper.LogHelper(); int totalCount = 0; public void ProcessRequest(HttpContext context) { HttpContext _Context = context; //接收文件 HttpRequest req = _Context.Request; if (req.Files.Count <= 0) { WriteStr("獲取服務(wù)器上傳文件失敗"); return; } HttpPostedFile _file = req.Files[0]; //獲取參數(shù) // string ext = req.Form["extention"]; string filename = req.Form["filename"]; //如果是int 類型當(dāng)文件大的時候會出問題 最大也就是 1.9999999990686774G int loaded = Convert.ToInt32(req.Form["loaded"]); totalCount += loaded; string newname = @"F:\JavaScript_Solution\H5Solition\H5Solition\Content\TempFile\"; newname += filename; //接收二級制數(shù)據(jù)并保存 Stream stream = _file.InputStream; if (stream.Length <= 0) throw new Exception("接收的數(shù)據(jù)不能為空"); byte[] dataOne = new byte[stream.Length]; stream.Read(dataOne, 0, dataOne.Length); FileStream fs = new FileStream(newname, FileMode.Append, FileAccess.Write, FileShare.Read, 1024); try { fs.Write(dataOne, 0, dataOne.Length); } finally { fs.Close(); stream.Close(); } _log.WriteLine((totalCount + dataOne.Length).ToString()); WriteStr("分段數(shù)據(jù)保存成功"); } private void WriteStr(string str) { HttpContext.Current.Response.Write(str); } public bool IsReusable { get { return true; } }
2.分段讀取文件為blob ,并使用ajax上傳到服務(wù)器,追加中止、繼續(xù)功能操作
分段讀取文件:
JS:
/* * 分段讀取文件為blob ,并使用ajax上傳到服務(wù)器 * 使用Ajax方式提交上傳數(shù)據(jù)文件大小應(yīng)該有限值,最好500MB以內(nèi) * 原因短時間過多的ajax請求,Asp.Net后臺會崩潰獲取上傳的分塊數(shù)據(jù)為空 * 取代方式,長連接或WebSocket */ var fileBox = document.getElementById('file'); var reader = null; //讀取操作對象 var step = 1024 * 1024 * 3.5; //每次讀取文件大小 var cuLoaded = 0; //當(dāng)前已經(jīng)讀取總數(shù) var file = null; //當(dāng)前讀取的文件對象 var enableRead = true;//標(biāo)識是否可以讀取文件 fileBox.onchange = function () { //獲取文件對象 file = this.files[0]; var total = file.size; console.info("文件大?。? + file.size); var startTime = new Date(); reader = new FileReader(); //讀取一段成功 reader.onload = function (e) { //處理讀取的結(jié)果 var result = reader.result; var loaded = e.loaded; if (enableRead == false) return false; //將分段數(shù)據(jù)上傳到服務(wù)器 uploadFile(result, cuLoaded, function () { console.info('loaded:' + cuLoaded + '----current:' + loaded); //如果沒有讀完,繼續(xù) cuLoaded += loaded; if (cuLoaded < total) { readBlob(cuLoaded); } else { console.log('總共用時:' + (new Date().getTime() - startTime.getTime()) / 1000); cuLoaded = total; } //顯示結(jié)果進(jìn)度 var percent = (cuLoaded / total) * 100; document.getElementById('Status').innerText = percent; document.getElementById('progressOne').value = percent; }); } //開始讀取 readBlob(0); //關(guān)鍵代碼上傳到服務(wù)器 function uploadFile(result, startIndex, onSuccess) { var blob = new Blob([result]); //提交到服務(wù)器 var fd = new FormData(); fd.append('file', blob); fd.append('filename', file.name); fd.append('loaded', startIndex); var xhr = new XMLHttpRequest(); xhr.open('post', '../ashx/upload2.ashx', true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { if (onSuccess) onSuccess(); } else if (xhr.status == 500) { //console.info('請求出錯,' + xhr.responseText); setTimeout(function () { containue(); }, 1000); } } //開始發(fā)送 xhr.send(fd); } } //指定開始位置,分塊讀取文件 function readBlob(start) { //指定開始位置和結(jié)束位置讀取文件 var blob = file.slice(start, start + step); reader.readAsArrayBuffer(blob); } //中止 function stop() { //中止讀取操作 console.info('中止,cuLoaded:' + cuLoaded); enableRead = false; reader.abort(); } //繼續(xù) function containue() { console.info('繼續(xù),cuLoaded:' + cuLoaded); enableRead = true; readBlob(cuLoaded); }
后臺代碼同上
3.分段讀取文件為二進(jìn)制數(shù)組 ,并使用ajax上傳到服務(wù)器
使用二進(jìn)制數(shù)組傳遞的方式,效率特別低,最終文件還與原始大小有些偏差
HTML內(nèi)容同上
JS:
/* * 分段讀取文件為二進(jìn)制數(shù)組 ,并使用ajax上傳到服務(wù)器 * 使用二進(jìn)制數(shù)組傳遞的方式,效率特別低,最終文件還與原始大小有些偏差 */ var fileBox = document.getElementById('file'); var reader = new FileReader(); //讀取操作對象 var step = 1024 * 1024; //每次讀取文件大小 var cuLoaded = 0; //當(dāng)前已經(jīng)讀取總數(shù) var file = null; //當(dāng)前讀取的文件對象 var enableRead = true;//標(biāo)識是否可以讀取文件 fileBox.onchange = function () { //獲取文件對象 if (file == null) //如果賦值多次會有丟失數(shù)據(jù)的可能 file = this.files[0]; var total = file.size; console.info("文件大?。? + file.size); var startTime = new Date(); //讀取一段成功 reader.onload = function (e) { //處理讀取的結(jié)果 var result = reader.result; var loaded = e.loaded; if (enableRead == false) return false; //將分段數(shù)據(jù)上傳到服務(wù)器 uploadFile(result, cuLoaded, function () { console.info('loaded:' + cuLoaded + '----current:' + loaded); //如果沒有讀完,繼續(xù) cuLoaded += loaded; if (cuLoaded < total) { readBlob(cuLoaded); } else { console.log('總共用時:' + (new Date().getTime() - startTime.getTime()) / 1000); cuLoaded = total; } //顯示結(jié)果進(jìn)度 var percent = (cuLoaded / total) * 100; document.getElementById('Status').innerText = percent; document.getElementById('progressOne').value = percent; }); } //開始讀取 readBlob(0); //關(guān)鍵代碼上傳到服務(wù)器 function uploadFile(result, startIndex, onSuccess) { var array = new Int8Array(result); console.info(array.byteLength); //提交到服務(wù)器 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('服務(wù)器出錯'); reader.abort(); } } //開始發(fā)送 xhr.send(fd); } } //指定開始位置,分塊讀取文件 function readBlob(start) { //指定開始位置和結(jié)束位置讀取文件 var blob = file.slice(start, start + step); reader.readAsArrayBuffer(blob); } //中止 function stop() { //中止讀取操作 console.info('中止,cuLoaded:' + cuLoaded); enableRead = false; reader.abort(); } //繼續(xù) function containue() { console.info('繼續(xù),cuLoaded:' + cuLoaded); enableRead = true; readBlob(cuLoaded); }
后臺代碼:
////// upload3 的摘要說明 /// public class upload3 : IHttpHandler { LogHelper.LogHelper _log = new LogHelper.LogHelper(); int totalCount = 0; public void ProcessRequest(HttpContext context) { HttpContext _Context = context; //接收文件 HttpRequest req = _Context.Request; string data = req.Form["file"]; //轉(zhuǎn)換方式一 //int[] intData = data.Split(',').Select(q => Convert.ToInt32(q)).ToArray(); //byte[] dataArray = intData.ToList().ConvertAll(x=>(byte)x).ToArray(); //轉(zhuǎn)換方式二 byte[] dataArray = data.Split(',').Select(q => int.Parse(q)).Select(q => (byte)q).ToArray(); //獲取參數(shù) string filename = req.Form["filename"]; //如果是int 類型當(dāng)文件大的時候會出問題 最大也就是 1.9999999990686774G int loaded = Convert.ToInt32(req.Form["loaded"]); totalCount += loaded; string newname = @"F:\JavaScript_Solution\H5Solition\H5Solition\Content\TempFile\"; newname += filename; try { // 接收二級制數(shù)據(jù)并保存 byte[] dataOne = dataArray; FileStream fs = new FileStream(newname, FileMode.Append, FileAccess.Write, FileShare.Read, 1024); try { fs.Write(dataOne, 0, dataOne.Length); } finally { fs.Close(); } _log.WriteLine((totalCount + dataOne.Length).ToString()); WriteStr("分段數(shù)據(jù)保存成功"); } catch (Exception ex) { throw ex; } } private void WriteStr(string str) { HttpContext.Current.Response.Write(str); } public bool IsReusable { get { return false; } } }
說明:使用Ajax方式上傳,文件不能過大,最好小于三四百兆,因為過多的連續(xù)Ajax請求會使后臺崩潰,獲取InputStream中數(shù)據(jù)會為空,尤其在Google瀏覽器測試過程中。
以上是html5中文件域+FileReader分段如何讀取文件并上傳到服務(wù)器的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!