HTML5 file fields + FileReader read files in segments and upload them to the server,

Source: Internet
Author: User

HTML5 file fields + FileReader read files in segments and upload them to the server,

Note: the file cannot be too large to be uploaded using Ajax. It is better to be smaller than 300 or 400 mb, because too many consecutive Ajax requests will cause the background to crash and the data obtained from InputStream will be blank, especially in the Google browser testing process.

1. Read the file Blob in simple segments and upload the file to the server using ajax.

<Div class = "container"> <div class = "panel-default"> <div class = "panel-heading"> multipart file reading: </div> <div class = "panel-body"> <input type = "file" id = "file"/> <blockquote style = "word-break: break-all; "> </blockquote> </div>

JS:

/** Multipart upload will throw an exception */var fileBox = document. getElementById ('file'); file. onchange = function () {// get the file object var file = this. files [0]; var reader = new FileReader (); var step = 1024*1024; var total = file. size; var cuLoaded = 0; console.info ("file size:" + file. size); var startTime = new Date (); // read a successful reader. onload = function (e) {// process the read result var loaded = e. loaded; // upload the multipart data to the server uploadFile (reader. result, cuLoaded, function () {console.info ('loaded: '+ cuLoaded + 'current:' + loaded); // if not, continue cuLoaded + = loaded; if (cuLoaded <total) {readBlob (cuLoaded);} else {console. log ('total time: '+ (new Date (). getTime ()-startTime. getTime ()/1000); cuLoaded = total ;}}); // specify the start position and read the file function readBlob (start) in multiple parts) {// specify the start position and end position to read the file // lele.info ('start: '+ start); var blob = file. slice (start, start + step); reader. readAsArrayBuffer (blob);} // start to read readBlob (0); // key code is uploaded to the server function uploadFile (result, startIndex, onSuccess) {var blob = new Blob ([result]); // submit it to the server 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 () ;}// start sending xhr. send (fd );}}

Background code:
 

/// <Summary> /// summary of upload2 /// </summary> public class upload2: IHttpHandler {LogHelper. logHelper _ log = new LogHelper. logHelper (); int totalCount = 0; public void ProcessRequest (HttpContext context) {HttpContext _ Context = context; // receives the file HttpRequest req = _ Context. request; if (req. files. count <= 0) {WriteStr ("failed to obtain the file Uploaded By the server"); return;} HttpPostedFile _ file = req. files [0]; // get the parameter // string ext = req. form ["extention"]; string filename = req. form ["filename"]; // if the file is of the int type, the maximum error may occur when the file is large, that is, 1.9999999990686774G int loaded = Convert. toInt32 (req. form ["loaded"]); totalCount + = loaded; string newname = @ "F: \ JavaScript_Solution \ H5Solition \ H5Solition \ Content \ TempFile \"; newname + = filename; // receives level-2 data and saves Stream = _ file. inputStream; if (stream. length <= 0) throw new Exception ("the received data cannot be blank"); 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 ("multipart data saved successfully");} private void WriteStr (string str) {HttpContext. current. response. write (str);} public bool IsReusable {get {return true ;}}

2. Read the object in parts as blob and upload the object to the server using ajax. append the object to stop and continue the function operation.

<Div class = "container"> <div class = "panel-default"> <div class = "panel-heading"> multipart file reading: </div> <div class = "panel-body"> <input type = "file" id = "file"/> <br/> <input type = "button" value = "Abort" onclick = "stop (); "/> & emsp; <input type =" button "value =" continue "onclick =" containue (); "/> <br/> <progress id =" progressOne "max =" 100 "value =" 0 "style =" width: 400px; "> </progress> <blockquote id =" Status "style =" word-break: break-all; "> </blockquote> </div>

JS:

/** Read the file in parts as blob and upload the file to the server using ajax * submit the file to upload data in Ajax mode. The file size should be limited. It is best to submit ajax requests within MB * due to too many reasons, asp. net background will crash to obtain the uploaded block data as null * replacement method, persistent connection or WebSocket */var fileBox = document. getElementById ('file'); var reader = null; // read operation object var step = 1024*1024*3.5; // the file size var cuLoaded = 0 is read each time; // The total number of currently read files var file = null; // The currently read file object var enableRead = true; // identifies whether the file fileBox can be read. onchange = function () {// obtain the file object file = this. files [0]; var total = file. size; console.info ("file size:" + file. size); var startTime = new Date (); reader = new FileReader (); // read a successful reader. onload = function (e) {// process the read result var result = reader. result; var loaded = e. loaded; if (enableRead = false) return false; // upload the multipart data to the server uploadFile (result, cuLoaded, function () {lele.info ('loaded: '+ cuLoaded +' ---- current: '+ loaded); // if not, continue cuLoaded + = loaded; if (cuLoaded <total) {readBlob (cuLoaded );} else {console. log ('total time: '+ (new Date (). getTime ()-startTime. getTime ()/1000); cuLoaded = total;} // display the result progress var percent = (cuLoaded/total) * 100; document. getElementById ('status '). innerText = percent; document. getElementById ('progressone '). value = percent;}) ;}// start to read readBlob (0); // key code is uploaded to the server function uploadFile (result, startIndex, onSuccess) {var blob = new Blob ([result]); // submit it to the server 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) {// lele.info ('request error, '+ xhr. responseText); setTimeout (function () {containue () ;}, 1000) ;}// start sending xhr. send (fd) ;}/// specify the start position, multipart Read file function readBlob (start) {// specify the start position and end position to read the file var blob = file. slice (start, start + step); reader. readAsArrayBuffer (blob);} // stop function stop () {// stop read operation lele.info ('abort, cuLoaded: '+ cuLoaded); enableRead = false; reader. abort ();} // continue function containue () {console.info ('continue, cuLoaded: '+ cuLoaded); enableRead = true; readBlob (cuLoaded );}

The background code is the same as above.

3. multipart File Reading is a binary array and uploaded to the server using ajax

The binary array transmission method is very inefficient, and the final file is somewhat different from the original size.

Same as HTML content

JS:

/** Multipart File Reading is a binary array and uploaded to the server using ajax * the binary array is used for transmission, which is very inefficient, the final file is somewhat different from the original size */var fileBox = document. getElementById ('file'); var reader = new FileReader (); // read the object var step = 1024*1024; // the size of each file read var cuLoaded = 0; // The total number of currently read files var file = null; // The currently read file object var enableRead = true; // identifies whether the file fileBox can be read. onchange = function () {// obtain the object if (file = null) // if the value is assigned multiple times, data may be lost. file = this. files [0]; var total = file. size; console.info ("file size:" + file. size); var startTime = new Date (); // read a successful reader. onload = function (e) {// process the read result var result = reader. result; var loaded = e. loaded; if (enableRead = false) return false; // upload the multipart data to the server uploadFile (result, cuLoaded, function () {lele.info ('loaded: '+ cuLoaded +' ---- current: '+ loaded); // if not, continue cuLoaded + = loaded; if (cuLoaded <total) {readBlob (cuLoaded );} else {console. log ('total time: '+ (new Date (). getTime ()-startTime. getTime ()/1000); cuLoaded = total;} // display the result progress var percent = (cuLoaded/total) * 100; document. getElementById ('status '). innerText = percent; document. getElementById ('progressone '). value = percent;}) ;}// start to read readBlob (0); // key code is uploaded to the server function uploadFile (result, startIndex, onSuccess) {var array = new Int8Array (result); console.info (array. byteLength); // submit to the server 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) {// lele.info (xhr. responseText); if (onSuccess) onSuccess ();} else if (xhr. status = 500) {lele.info ('server error'); reader. abort () ;}// start sending xhr. send (fd) ;}/// specify the start position, multipart Read file function readBlob (start) {// specify the start position and end position to read the file var blob = file. slice (start, start + step); reader. readAsArrayBuffer (blob);} // stop function stop () {// stop read operation lele.info ('abort, cuLoaded: '+ cuLoaded); enableRead = false; reader. abort ();} // continue function containue () {console.info ('continue, cuLoaded: '+ cuLoaded); enableRead = true; readBlob (cuLoaded );}

Background code:

/// <Summary> /// summary of upload3 /// </summary> public class upload3: IHttpHandler {LogHelper. logHelper _ log = new LogHelper. logHelper (); int totalCount = 0; public void ProcessRequest (HttpContext context) {HttpContext _ Context = context; // receives the file HttpRequest req = _ Context. request; string data = req. form ["file"]; // conversion method 1 // int [] intData = data. split (','). select (q => Convert. toInt32 (q )). toArray (); // byte [] dataArray = intData. toList (). convertAll (x => (byte) x ). toArray (); // conversion method 2 byte [] dataArray = data. split (','). select (q => int. parse (q )). select (q => (byte) q ). toArray (); // obtain the string filename = req. form ["filename"]; // if the file is of the int type, the maximum error may occur when the file is large, that is, 1.9999999990686774G int loaded = Convert. toInt32 (req. form ["loaded"]); totalCount + = loaded; string newname = @ "F: \ JavaScript_Solution \ H5Solition \ H5Solition \ Content \ TempFile \"; newname + = filename; try {// receive level-2 data and save 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 ("multipart data saved successfully");} catch (Exception ex) {throw ex ;}} private void WriteStr (string str) {HttpContext. current. response. write (str);} public bool IsReusable {get {return false ;}}}

Summary

The above is a small part of the HTML5 file domain + FileReader to read files in segments and upload them to the server. I hope it will help you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.