search
HomeWeb Front-endH5 TutorialHTML5 WebSocket implementation of multiple file uploads at the same time

In traditional HTTP applications, it is very troublesome to upload multiple files at the same time and check the upload progress. Of course, there are also some SWF-based file upload components that provide this convenience. In HTML5, it is The control of file reading and uploading is very flexible. HTML5 provides a series of AIPs for file reading, including calculating the content of a certain part of the file. It is also very convenient. Combined with Websocket, file transmission becomes more convenient and flexible. The following is a simple way to implement multiple file upload applications at the same time by using HTML5 combined with websocet.

Achieve functions

A rough preview of the functions that need to be done:

HTML5 WebSocket implementation of multiple file uploads at the same time

The main function is that users can directly drag and drop the files in the folder to the web page and upload them, and the upload progress information will be displayed during the upload process.

FileInfo Class encapsulation

In order to facilitate reading file information, a simple object class for reading file information is encapsulated based on 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() * 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++) {

        binary += String.fromCharCode(bytes[i])

    }

    return window.btoa(binary);

}

FileInfo.prototype.OnLoadData = function (evt) {

    var obj = evt.target["tag"];

 

    if (evt.target.readyState == FileReader.DONE) {

        obj.DataBuffer = evt.target.result;

        if (obj.LoadCallBack != null)

            obj.LoadCallBack(obj);

 

    }

    else {

        if (obj.UploadError != null)

            obj.UploadError(fi, evt.target.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)

        count = 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);

        }

    });

 

}

## The processing of the
# class is very simple. Initialize some file information through file initialization and specify the block size, such as the number of pages, page size, etc. Of course, the most important thing is to encapsulate the Upload method corresponding to the file, which is used to store the file block information. The base64 information is packaged and sent to the server through Websocket.


File drag and drop
There is no need to do complicated things to accept system file drag and drop in HTML5. You only need to bind relevant events to the container element.


function onDragEnter(e) {

            e.stopPropagation();

            e.preventDefault();

        }

 

        function onDragOver(e) {

            e.stopPropagation();

            e.preventDefault();

            $(dropbox).addClass(&#39;rounded&#39;);

        }

 

        function onDragLeave(e) {

            e.stopPropagation();

            e.preventDefault();

            $(dropbox).removeClass(&#39;rounded&#39;);

        }

 

        function onDrop(e) {

            e.stopPropagation();

            e.preventDefault();

            $(dropbox).removeClass(&#39;rounded&#39;);

            var readFileSize = 0;

            var files = e.dataTransfer.files;

            if (files.length > 0) {

                onFileOpen(files);

            }

 

        }


You only need to obtain the relevant drag and drop files during the onDrop process, which may be passed through some HTML5 Tutorials can help.

At this time, you only need to build the relevant 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);

                }

            }

        }


Upload through the UploadProcess event File progress information is updated with a setting


function onUploadProcess(file) {

            $(&#39;#p_&#39; + file.ID).progressbar({ value: (file.PageIndex / file.Pages) * 100,

                text: file.FileName + &#39;[&#39; + file.UploadBytes + &#39;/&#39; + file.Size + &#39;]&#39;

            });

        }



C#Server
With the help of Beetle’s support for websocket, the corresponding service The implementation on the end is very simple


/// <summary>

    /// Copyright © henryfan 2012        

    ///CreateTime:  2012/12/14 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, one is to upload file request, and the other is to upload file block receiving method.


Summary
Only the above simple code can realize the function of uploading multiple files at the same time. Here, json is used to process the uploaded information, so the file stream needs to be encoded with base64. Since the data submitted by websocket browsing generally has MASK processing and the loss of base64 is relatively heavy, in fact websocket provides a stream packet format (arraybuffer); of course, this kind of processing is not as convenient and simple as json in operation. .

Download code: WebSocketUpload.rar


The above is the content of the example of HTML5 WebSocket realizing simultaneous uploading of multiple files. For more related content, please pay attention to the PHP Chinese website (www .php.cn)!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML5 Features: The Core of H5HTML5 Features: The Core of H5May 04, 2025 am 12:05 AM

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.

H5: Exploring the Latest Version of HTMLH5: Exploring the Latest Version of HTMLMay 03, 2025 am 12:14 AM

HTML5isamajorrevisionoftheHTMLstandardthatrevolutionizeswebdevelopmentbyintroducingnewsemanticelementsandcapabilities.1)ItenhancescodereadabilityandSEOwithelementslike,,,and.2)HTML5enablesricher,interactiveexperienceswithoutplugins,allowingdirectembe

Beyond Basics: Advanced Techniques in H5 CodeBeyond Basics: Advanced Techniques in H5 CodeMay 02, 2025 am 12:03 AM

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

H5: The Future of Web Content and DesignH5: The Future of Web Content and DesignMay 01, 2025 am 12:12 AM

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

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.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

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.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

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 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)