說明:使用Ajax方式上傳,文件不能過大,最好小於三四百兆,因為過多的連續Ajax請求會使後台崩潰,獲取InputStream中數據會為空,尤其在Google瀏覽器測試過程中。
1.簡單分段讀取文件為Blob,ajax上傳到服務器
<div class=container> <div class=panel panel-default> <div class=panel-heading>分段讀取文件:</div> <div class=panel-body> <input type=file id=file / > <blockquote style=word-break:break-all;></blockquote> </div> </div></div>
JS:
/** 分段讀取文件為blob ,並使用ajax上傳到服務器* 分段上傳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) { //處理讀取的結果var loaded = e.loaded; //將分段數據上傳到服務器uploadFile(reader.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; } }); } //指定開始位置,分塊讀取文件function readBlob(start) { //指定開始位置和結束位置讀取文件//console.info('start:' + start); var blob = file.slice(start, start + step); reader.readAsArrayBuffer(blob); } //開始讀取readBlob(0); //關鍵代碼上傳到服務器function uploadFile(result, startIndex, onSuccess) { var blob = new Blob([result]); //提交到服務器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(); } } //開始發送xhr.send( fd); }}
後台代碼:
/// <summary>/// upload2 的摘要說明/// </summary>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(獲取服務器上傳文件失敗); return; } HttpPostedFile _file = req.Files[0] ; //獲取參數// string ext = req.Form[extention]; string filename = req.Form[filename]; //如果是int 類型當文件大的時候會出問題最大也就是1.9999999990686774G int loaded = Convert .ToInt32(req.Form[loaded]); totalCount += loaded; string newname = @F:/JavaScript_Solution/H5Solition/H5Solition/Content/TempFile/; newname += filename; //接收二級制數據並保存Stream stream = _file.InputStream; if (stream.Length <= 0) throw new Exception(接收的數據不能為空); 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(分段數據保存成功); } private void WriteStr(string str) { HttpContext.Current.Response.Write(str ); } public bool IsReusable { get { return true; } }
2.分段讀取文件為blob ,並使用ajax上傳到服務器,追加中止、繼續功能操作
<div class=container> <div class=panel panel-default> <div class=panel-heading>分段讀取文件:</div> <div class=panel-body> <input type=file id=file / > <br /> <input type=button value=中止onclick=stop(); />  <input type=button value=繼續onclick=containue(); /> <br /> <progress id=progressOne max= 100 value=0 style=width:400px;></progress> <blockquote id=Status style=word-break:break-all;></blockquote> </div> </div></div>
JS:
/** 分段讀取文件為blob ,並使用ajax上傳到服務器* 使用Ajax方式提交上傳數據文件大小應該有限值,最好500MB以內* 原因短時間過多的ajax請求,Asp.Net後台會崩潰獲取上傳的分塊數據為空* 取代方式,長連接或WebSocket*/var fileBox = document.getElementById('file');var reader = null; //讀取操作對象var step = 1024 * 1024 * 3.5; //每次讀取文件大小var cuLoaded = 0; //當前已經讀取總數var file = null; //當前讀取的文件對象var enableRead = true;//標識是否可以讀取文件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) { //處理讀取的結果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 blob = new Blob([result]); //提交到服務器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); } } //開始發送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);}
後台代碼同上
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);}
後台代碼:
/// <summary>/// upload3 的摘要說明/// </summary>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]; //轉換方式一//int[] intData = data.Split(',').Select( q => Convert.ToInt32(q)).ToArray(); //byte[] dataArray = intData.ToList().ConvertAll(x=>(byte)x).ToArray(); //轉換方式二byte[ ] dataArray = data.Split(',').Select(q => int.Parse(q)).Select(q => (byte)q).ToArray(); //獲取參數string filename = req.Form [filename]; //如果是int 類型當文件大的時候會出問題最大也就是1.9999999990686774G int loaded = Convert.ToInt32(req.Form[loaded]); totalCount += loaded; string newname = @F:/ JavaScript_Solution/H5Solition/H5Solition/Content/TempFile/; newname += filename; try { // 接收二級制數據並保存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 (分段數據保存成功); } catch (Exception ex) { throw ex; } } private void WriteStr(string str) { HttpContext.Current.Response.Write(str); } public bool IsReusable { get { return false; } }}總結
以上所述是小編給大家介紹的HTML5 文件域+FileReader 分段讀取文件並上傳到服務器,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VeVb武林網網站的支持!