Note: Upload it with AJAX, the file cannot be too large, it is best to be less than three or four hundred trillion, because excessive continuous AJAX requests will collapse the background, and the data in InputStream will be empty, especially during the Google browser test.
1. Simple segment reading files are blob, AJAX uploads to the server
<div class = Container> <div class = Panel Panel-DEFAULT> <div class = Panel-Heading> Reading file: < /div> <div class = panel-body> <input type = file id = file / > <blockquote style = word-break: break-all;> </blockquote> </div> </div> </div>
Js:
/** Segmentation files are blobs, and uploaded to the server* segments to upload exe files with Ajax will throw an exception* /var filebox = document.GetelementByid ('file'); /获取文件对象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 (); // Read a section of successful Reader.Onload = Function (e) {// Treatment the results of the read reading = e.loaded; // Upload segment data to the server UploadFile (Reader.Result, Culoaded, Function () {Console.info ('Loaded:' + Culoaded + 'Current:' + Loaded); // If not finished, continue Culoaded + = loade d; Culoaded <Total) {Readblob (Culoaded);} Else {console.log ('A total:' + (new date (). Gettime () - Starttime.gettime ()) / 1000); Culoaded = Total;}); / / Specify the starting position, read the file function function readblob (start) {// Specify the starting position and the end position read file //console.info_Start: ' + Start); VAR Blob = File.slice (Start, Start, Start, Start, Start, Start, Start + step); Reader.ReadasarrayBuffer (blob);} // start reading ReadBlob (0); // The key code Upload to the server function uploadFile (result, startIndex, onSuccess) {var blob = NE w blob ([result]); // Submit 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.R.Responsetext); if (onsuccess) onSuccess ();} // Start send xhr.send ( fd);}}
Background code:
/// <summary> /// UPLOAD2 Abstract Instructions /// </Summary> Public Class Upload2: IHTTPHANDLER {Loghelper.loghelper_LOG = New Loghelper.loghelper (); int OUNT = 0; Public Void ProcessRequest (HTTPCONTEXT Context) {Httpcontext_Context = context; // Receive file httprequest repk = _Context.Request; if (req.files.count <= 0) {Writestr (fail to obtain the server upload file); return;} httpppp OSTEDFILE _file = REQ.FILES [0] ; // Get parameters // string ext = req.form [extension]; string filename = reQ.Form [filename]; // If it is when the file is large, the biggest problem is 1.9999999999906774G INT LOADED = C. Onvert .Toint32 (Req.form [loaded]); TotalCount += Loaded; String News = @F:/Javascript_solution/H5Solition/Content/TEMPFILE/; WNAME += FILENAME; // Receive the second -level data and save Stream Stream = _file.inputstream; if (stream.length <= 0) Throw New Exception (the receiving data cannot be empty); byte [] dataOne = New byte [stream.length]; stream.Read (dataOne, 0, DataONE.L English );; NewName, Filemode.append, FileAccess.write, Fileshare.read, 1024); Try {fs.write (DataOne.Length);} FINALL y {fs.close (); stream .Close ();} _log.writeLine (TotalCount + DataONE.Length) .tring ()); Writestr (successfully saved segment data);} Private Void WritStr (String STR) {httpcontext.cur Rent.Response.write (STR );} Public Bool Isreusable {get {Return True;}}
2. Read the file in sections to BLOB, and upload it to the server with AJAX.
<div class = Container> <div class = Panel Panel-DEFAULT> <div class = Panel-Heading> Reading file: < /div> <div class = panel-body> <input type = file id = file / > <br /> <input type = Button value = Stop onClight = Stop (); /> & EMSP; <input Type = Button Value = Continue onClick = Containue (); Progressone Max = 100 value = 0 style = width: 400px;> </Progress> <blockquote ID = Status style = word-break: break-all;> </blockquote> </div> </div>
Js:
/** Segmentation files are blobs, and upload it to the server by AJAX* Use Ajax to submit upload data file size. It should be limited. It is best to be within 500MB. The segmentation data for uploading is empty * replacement method, long connection or websocket */var filebox = document.GetelementByid ('file'); VAR Reader = Null; // Every time I read the file size, varocoaded = 0; // The total number of read the total number var file = null; // The currently read file object varoon every = true; Function () {// Get the file object file = this.files [0]; varual = file.size; console.info (file size: + file.size); var Starttime = New Date (); Reader = New FILEAD errand (); // Read a period of successful Reader.Onload = Function (e) {// The result of the reading read = 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 ('A total:' + () + (). Gettime () - Starttime.gettime ()) / 1000 );; = Total;} // Display results progress = (Culoaded /Total) * 100; Document.GetelementByid ('STATUS'). Innertext; Ressone '). Value = Percent;});} // Start reading Readblob (0); // Key code Upload to the server Function UploadFile (Result, StartIndex, onsuccess) {Var Blob = New Blob ([Result]); // () ; fd.append ('File', Blob); fd.append ('Filename', File.name); fd.append ('loaded', startindex); var xhr = new xmlhttpRequest (); xhr.op en ('post ',' ../ashx/upload2.ashx ', true); XHR.OnReadyStateChange = Function () {if (xhr.reamState == 4 && XHR.Status ==) {ifccess) ss ();} else if (xhr.status == 500) {//console.info ('Request error,' + xhr.Responsetext); settimeout (function () {containing ();},} // start sending xhr .send (fd);}} // Specify the starting position, read the file function readblob (start) {// Specify the starting position and the end position, read file var blob = file.slice (start, start + step); Reader.ReadasarrayBuffer (blob);} // suspend the function stop () {// Console.info ('stop, Culoaded:' + Culoaded); enableread = false.abort ();} // Continue Function Containue () {console.info ('Continue, Culoaded:' + Culoaded); enableread = true; Readblob (Culoaded);}
Background code with above
3. Read the files in sections to binary array, and upload it to the server with AJAX
The use of binary arrays is particularly low, and the final file is a bit deviated with the original size
HTML content is the same as above
Js:
/** Seg segmented reading files are binary array, and upload to the server by AJAX to use the method of transmitting using binary arrays. The efficiency is particularly low. The final file is also a bit deviated with the original size*/var FileBox = Document.GetelementByid ('File' ); Var Reader = New FILEREADER (); // Read the operating object Var Step = 1024 * 1024; // Every time you read the file size, varoaded = 0; // The total number of read the total number var foot = null; // The currently read file object var enableread = true; // The identification can read the file filebox.onchange = function () {// Get the file object if (file == null) // If the value is assigned multiple times, the data will be lost. May 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) {// The results of the reading read = reader.Result; var loaded = e.loaded; if (enableread == false) Return false; // Upload segment data to the server UPLOADFILE (Result, Cuload ED, Function () {Console.info ('Loaded:' + Culoaded + '---- Current:' + Loaded); // If not finished, continue Culoaded + = LOADED; if (Culoaded <Total) { Oaded) ;} Else {console.log ('Total time:' + (new date (). Gettime () - starttime.gettime ()) /1000); Culoaded = Total;} // Display results progress = (Culoaded / Total) * 100; Document.GetelementByid ('STATUS'). Innertext = Percent; Document.GetelementByid ('Progressone'). Value = Percent;});} // Start reading and start reading. Readblob (0); // Key code Upload Go to the server function uploadFile (Result, StartIndex, onsuccess) {var array = New Int8array (Result); console.info (array.bytelength); // Submit to the server VAR FD = New For mdata (); fd.append ('file' , array); fd.append ('filename', file.name); fd.append ('loaded', startindex); var xhr = new xmlhttprequest (); xhr.open ('post', '../as. hx/ Upload3.Ashx ', TRUE); xhr.onreadyStateChange = Function () {if (xhr.readyState == 4 && XHR.Status ==) {// console.info (xhr.Responsetext); if (onsuccess) onSuccess ( );} else if (xhr.status == 500) {console.info ('server error'); reader.abort ();} // Start sending xhr.send (fd);}} // Specify starting position. Read the file funch readblob (start) {// Specify the starting position and the end position. P () {// Console.info ('Disglement, Culoaded:' + Culoaded); enableread = false; Reader.abort ();} // Continue the function containue () {console.info (' Loaded : ' + Culoaded); enableread = true; readblob (Culoaded);}
Background code:
/// <summary> /// UPLOAD3 Abstract Instructions /// </Summary> Public Class Upload3: IHTTPHANDLER {loghelper.loghelper_log = new logHelper.loghelper (); int OUNT = 0; Public Void ProcessRequest (HTTPCONTEXT Context) {Httpcontext_Context = Context; // Receive file httprequest repk = _Context.Request; String data = reQ.Form [file]; // int [] intData = data.Split (',' ) .Select (Select ( q => convert.toint32 (q)). Toarray (); // byte []] dataarray = intData.tolist (). ConvertAll (x => (byte) .toarray (); // Conversion method 2 byte [ ] DataArray = Data.Split (','). Select (q => int.parse (q)). Select (q => (byte) .toarray (); // Get the parameter string filename = reQ.FORM [FILENAME]; // If it is an int type, the biggest problem will be 1.99999999990686774g int loaded = Convert.toint32 (Req.Form [loaded]); TOTALCOUNT += loaded; wname = @F:/ Javascript_solution/h5solition/h5solition/content/test/tempfile/; newName += filename; try {// to receive second -level 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 ); Writestr (Successfully preserved segmented data);} Catch (Exception EX) {Throw EX;}} Private Void WriteStr (String Str) {httpcontext.Response.write (str);} PUBLIC BOOL isre usable {get {return false;} }}Summarize
The above is the HTML5 file domain+FileRereader read files and uploaded it to the server. I hope it will be helpful to everyone. If you have any questions, please leave me a message. Xiaobian will reply to everyone in time. Thank you very much for your support for the VEVB Wulin website!