1.简单分段读取文件为Blob,ajax上传到服务器
<p class="container"> <p class="panel panel-default"> <p class="panel-heading">分段读取文件:</p> <p class="panel-body"> <input type="file" id="file" /> <blockquote style="word-break:break-all;"></blockquote> </p> </p> </p>
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上传到服务器,追加中止、继续功能操作
<p class="container"> <p class="panel panel-default"> <p class="panel-heading">分段读取文件:</p> <p 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> </p> </p> </p>
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; } } }
说明:使用Ajax方式上传,文件不能过大,最好小于三四百兆,因为过多的连续Ajax请求会使后台崩溃,获取InputStream中数据会为空,尤其在Google浏览器测试过程中。
以上是html5中文件域+FileReader分段读取文件并上传到服务器的案例的详细内容。更多信息请关注PHP中文网其他相关文章!

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5开发需要掌握的工具和框架包括Vue.js、React和Webpack。1.Vue.js适用于构建用户界面,支持组件化开发。2.React通过虚拟DOM优化页面渲染,适合复杂应用。3.Webpack用于模块打包,优化资源加载。

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5通过语义化元素和ARIA属性提升网页的可访问性和SEO效果。1.使用、、等元素组织内容结构,提高SEO。2.ARIA属性如aria-label增强可访问性,辅助技术用户可顺利使用网页。

"h5"和"HTML5"在大多数情况下是相同的,但它们在某些特定场景下可能有不同的含义。1."HTML5"是W3C定义的标准,包含新标签和API。2."h5"通常是HTML5的简称,但在移动开发中可能指基于HTML5的框架。理解这些区别有助于在项目中准确使用这些术语。

H5,即HTML5,是HTML的第五个版本,它为开发者提供了更强大的工具集,使得创建复杂的网页应用变得更加简单。H5的核心功能包括:1)元素允许在网页上绘制图形和动画;2)语义化标签如、等,使网页结构清晰,利于SEO优化;3)新API如GeolocationAPI,支持基于位置的服务;4)跨浏览器兼容性需要通过兼容性测试和Polyfill库来确保。

如何创建 H5 链接?确定链接目标:获取 H5 页面或应用程序的 URL。创建 HTML 锚点:使用 <a> 标记创建锚点并指定链接目标URL。设置链接属性(可选):根据需要设置 target、title 和 onclick 属性。添加到网页:将 HTML 锚点代码添加到希望链接出现的网页中。

解决 H5 兼容问题的方法包括:使用响应式设计,允许网页根据屏幕尺寸调整布局。采用跨浏览器测试工具,在发布前测试兼容性。使用 Polyfill,为旧浏览器提供对新 API 的支持。遵循 Web 标准,使用有效的代码和最佳实践。使用 CSS 预处理器,简化 CSS 代码并提高可读性。优化图像,减小网页大小并加快加载速度。启用 HTTPS,确保网站的安全性。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

Atom编辑器mac版下载
最流行的的开源编辑器

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

SublimeText3 Linux新版
SublimeText3 Linux最新版

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能