Home > Web Front-end > H5 Tutorial > H5+WebSocket uploads multiple files at the same time

H5+WebSocket uploads multiple files at the same time

php中世界最好的语言
Release: 2018-03-26 14:01:45
Original
2640 people have browsed it

This time I will bring you H5+WebSocket to upload multiple files at the same time. What are the precautions for H5+WebSocket to upload multiple files at the same time? The following is a practical case, let’s take a look.

It is very troublesome to upload files in traditional HTTP applications and want 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 This kind of convenience. When it comes to controlling the reading and uploading of files under HTML5, it is very flexible. HTML5 provides a series of AIPs for file reading, including calculating the content of a certain piece of the file. It is also very convenient to combine the Websocket for file reading. The transmission becomes more convenient and flexible. By using HTML5 combined with websocet, we can simply implement multiple file upload applications at the same time.

Achieve functions

Give a rough preview of the functions that need to be done:

The main function is that users can directly drag and drop files in the folder to the web page and upload them. During the upload process Display upload progress information.

FileInfoClass encapsulation

For the convenience of

reading file information , based on the original File, a simple object class for reading file information is encapsulated. The processing of the

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);
        }
    });
 
}
Copy after login

class is very simple. Some file information, such as the number of pages, is initialized by initializing the file and specifying the block size. Page size, etc. Of course, the most important thing is to encapsulate the Upload method corresponding to the file, which is used to package the file block information into base64 information and send it to the server through Websocket.

File Drag and Drop

You don’t need to do complicated things to accept drag-and-drop of system files 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);
            }
 
        }
Copy after login
Only need to do it in onDrop Just get the relevant drag-and-drop files during the process. These may be helped by some HTML5 tutorials.

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);
                }
            }
        }
Copy after login

Use the UploadProcess event to set and update the upload file progress information

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;
            });
        }
Copy after login

C#Server

With the help of Beetle’s support for websocket, the corresponding server implementation 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";
        }
    }
Copy after login
There are two server methods Each one is an upload file request, and an upload file block receiving method.

Summary

Only the above simple code can achieve many Simultaneous file upload function uses json 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 plus base64, the loss is relatively heavy. In fact, Websocket provides a streaming data packet format (arraybuffer); of course, this kind of processing is not as convenient and simple as json in operation.

Download code: WebSocketUpload.rar

I believe I have read the case in this article You have mastered the method. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

spring mvc+localResizeIMG implements H5 image compression and upload

What are the methods for H5 form verification

H5 realizes rotating three-dimensional Rubik's Cube

The above is the detailed content of H5+WebSocket uploads multiple files at the same time. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template