The HTML5-WebSocket enables simultaneous upload of multiple files

Source: Internet
Author: User

It is very troublesome for traditional HTTP applications to upload multiple files at the same time and view the upload progress, of course, there are also some SWF-based File Upload components to provide this convenience. in HTML5, the control on file reading and uploading is very flexible. HTML5 provides a series of AIPS for file reading, including reading a part of a file, it is more convenient and flexible to transfer files with websocket. the following uses HTML5 and websocet to Easily upload multiple files to the application at the same time.

Implement Functions

Preview The functions you need:

The main function is that you can directly drag and drop folder files to a webpage and upload them to display the upload progress information during the upload process.

Fileinfo class Encapsulation

To facilitate reading file information, an object class for reading simple file information is encapsulated on the basis of the original file.

Function fileinfo (file, pagesize) {This. size = file. size; this. file = file; this. filetype = file. type; this. filename = file. name; this. pagesize = pagesize; this. pageindex = 0; this. pages = 0; this. uploaderror = NULL; this. uploadprocess = NULL; this. databuffer = NULL; this. uploadbytes = 0; this. id = math. floor (math. random () x 0x10000 ). tostring (16); this. loadcallback = NULL; If (math. floor (this. size % This. pagesize)> 0) {This. pages = math. floor (this. size/This. pagesize) + 1;} else {This. pages = math. floor (this. size/This. pagesize) ;}} fileinfo. prototype. reset = function () {This. pageindex = 0; this. uploadbytes = 0;} fileinfo. prototype. tobase64string = function () {var binary = ''var bytes = new uint8array (this. databuffer) var Len = bytes. bytelength; For (VAR I = 0; I <Len; I ++) {B Inary + = string. fromcharcode (Bytes [I])} return window. btoa (Binary);} fileinfo. prototype. onloaddata = function (EVT) {var OBJ = evt.tar get ["tag"]; If (evt.tar get. readystate = filereader. done) {obj. databuffer = evt.tar get. result; If (obj. loadcallback! = NULL) obj. loadcallback (OBJ);} else {If (obj. uploaderror! = NULL) obj. uploaderror (FI, evt.tar get. error) ;}} fileinfo. prototype. load = function (completed) {This. loadcallback = completed; If (this. filereader = NULL | this. filereader = undefined) This. filereader = new filereader (); var reader = This. filereader; reader ["tag"] = This; reader. onloadend = This. onloaddata; var COUNT = This. size-this. pageindex * This. pagesize; If (count> This. pagesize) coun T = This. pagesize; this. uploadbytes + = count; var blob = This. file. slice (this. pageindex * This. pagesize, this. pageindex * This. pagesize + count); reader. readasarraybuffer (BLOB) ;}; fileinfo. prototype. onuploaddata = function (File) {var channel = file. _ channel; var url = file. _ URL; channel. send ({URL: URL, parameters: {fileid: file. ID, pageindex: file. pageindex, pages: file. pages, base64data: file. Tobase64string () }}, function (result) {If (result. status = NULL | result. status = undefined) {file. pageindex ++; If (file. uploadprocess! = NULL) file. uploadprocess (File); If (file. pageindex <file. Pages) {file. Load (file. onuploaddata) ;}} else {If (file. uploaderror! = NULL) file. uploaderror (file, Data. status) ;}}) ;}fileinfo. prototype. upload = function (Channel, URL) {var Fi = This; channel. send ({URL: URL, parameters: {filename: fi. filename, size: fi. size, fileid: fi. id }}, function (result) {If (result. status = NULL | result. status = undefined) {fi. _ channel = channel; FI. _ url = result. data; FI. load (Fi. onuploaddata);} else {If (file. uploaderror! = NULL) file. uploaderror (FI, result. Status );}});}

Class processing is very simple. Some file information is implemented through file initialization and specifying the part size, such as the page size of the number of pages. of course, the most important thing is to encapsulate the file's upload method, which is used to package the file block information into base64 information and send it to the server through websocket.

Drag and Drop files

In HTML5, you do not need to perform complicated tasks by dragging system files. You only need to bind related events to container elements.

Function ondragenter (e) {e. stoppropagation (); E. preventdefault ();} function ondragover (e) {e. stoppropagation (); E. preventdefault (); $ (Dropbox ). addclass ('rounded');} function ondragleave (e) {e. stoppropagation (); E. preventdefault (); $ (Dropbox ). removeclass ('rounded');} function ondrop (e) {e. stoppropagation (); E. preventdefault (); $ (Dropbox ). removeclass ('rounded'); var readfilesize = 0; var files = E. datatransfer. files; If (files. length> 0) {onfileopen (Files );}}

You only need to get the relevant drag and drop files in the ondrop process, these may be through some HTML5 tutorials can get help, see the http://www.html5rocks.com/zh/tutorials/file/dndfiles/ in detail

In this case, you only need to build the fileinfo object for the selected file and call the upload method.

Function onfileopen (Files) {If (files. length> 0) {for (VAR I = 0; I <files. length; I ++) {var info = new fileinfo (files [I], 32768); uploads. push (Info); info. uploadprocess = onuploadprocess; adduploaditem (Info );}}}

Use the uploadprocess event to update the progress of the uploaded file.

 
Function onuploadprocess (File) {$ ('# P _' + file. ID ). progressbar ({value: (file. pageindex/file. pages) * 100, text: file. filename + '[' + file. uploadbytes + '/' + file. size + ']'});}
C # Server

With beetle's support for websocket, the implementation of the corresponding server is very simple.

/// <Summary> // copyright henryfan 2012 // Email: henryfan@msn.com // homepage: http://www.ikende.com // createtime: 21:13:34 /// </Summary> public class handler {public void uploadpackage (string fileid, int pageindex, int pages, string base64data) {console. writeline ("fileid: {2}, pageindex: {0} pages: {1} datalength: {3}", pageindex, pages, fileid, base64data. length);} Public String uploadfile (string fileid, string filename, Long SIZE) {console. writeline ("fileid: {2}, filename: {0} size: {1}", filename, size, fileid); Return "handler. uploadpackage ";}}

There are two server-side Methods: upload a file request and upload a file block receiving method.

Summary

Only the above simpleCodeThis enables simultaneous upload of multiple files. JSON is used to process the uploaded information. Therefore, the file stream must be encoded in base64 format, because the data submitted by websocket browsing generally has mask Processing plus base64, the loss is relatively heavy. In fact, websocket provides the stream data packet format (arraybuffer ); of course, this kind of processing is not convenient and simple in terms of JSON operations.

Download Code: websocketupload.rar (642.65 KB)

Demo address: http://html5.ikende.com/upload.htm using chrome or ie10 Browser

 

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.