This time I will bring you the method of H5reading filesand uploading them to the server. What are the precautions of the method of H5 reading files and uploading them to the server? The following are Let’s take a look at practical cases.
Note: When uploading using Ajax, the file should not be too large, preferably less than three to four hundred megabytes, because too many consecutive Ajax requests will cause the background to crash and the data in the InputStream will be empty, especially when browsing on Google during device testing.
1. Simply read the file into Blobs in segments and upload it to the server with ajax
<p> </p><p> </p><p>分段读取文件:</p> <p> <input> </p><blockquote></blockquote>
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 <p style="text-align: left;">Backend code: <br> </p><pre class="brush:php;toolbar:false">/// <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 <p style="text-align: left;"> 2. Read the file into blobs in sections, and upload it to the server using ajax, adding the stop and continue function operations</p><pre class="brush:php;toolbar:false"><p> </p><p> </p><p>分段读取文件:</p> <p> <input> <br> <input> <input> <br> <progress></progress> </p><blockquote></blockquote>
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 <p style="text-align: left;">The background code is the same as above</p><p style="text-align: left;">3. Read the file in segments into a binary array and upload it to the server using ajax</p><p style="text-align: left;"> Using binary array transfer is very inefficient, and the final file still deviates somewhat from the original size</p><p style="text-align: left;">HTML content is the same as above</p><p style="text-align: left;">JS: </p><pre class="brush:php;toolbar:false">/* * 分段读取文件为二进制数组 ,并使用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 <p style="text-align: left;">Backend code: </p><pre class="brush:php;toolbar:false">/// <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; } } }
I believe you have mastered the method after reading the case in this article, and there will be more exciting things Please pay attention to other related articles on php Chinese website!
Recommended reading:
How to achieve the animation effect of picture rotation in html5
H5 implements desktop notification
The above is the detailed content of How to read files in H5 and upload them to the server. For more information, please follow other related articles on the PHP Chinese website!

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor
