欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

HTML5+WebSocket实现多文件同时上传的实例

程序员文章站 2023-11-23 22:18:16
本篇文章主要介绍了HTML5-WebSocket实现多文件同时上传的实例,HTML5结合Websocket进行文件的传输就变得更加方便和灵活,有兴趣的可以了解一下。 ... 16-12-29...

在传统的http应用上传文件想要同时上传多个文件并查看上传进度是一件很麻烦的事情,当然现在也有一些基于swf的文件上传组件提供这种的便利性.到了html5下对文件的读取和上传的控制方面就非常灵活,html5提供一系列的aip进行文件读取,包括计取文件某一块的内容也非常方便,结合websocket进行文件的传输就变得更加方便和灵活.下面通过使用html5结合websocet简单地实现多文件同时上传应用.

实现功能

大概预览一下需要做的功能:

HTML5+WebSocket实现多文件同时上传的实例

主要功能是用户可以直接把文件夹的文件直接拖放到网页中,并进行上传,在上传的过程中显示上传进度信息.

fileinfo类封装

为了方便读取文件信息,在原有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);

        }

    });

 

} 

类的处理很简单,通过file初始化并指定分块大小来实始化一些文件信息,如页数量页大小等.当然最重要还封装文件对应的upload方法,用于把文件块信息打包成base64信息通过websocket的方式发送到服务器.

文件拖放

在html5中接受系统文件拖放进来并不需要做复杂的事情,只需要针对容器元素绑定相关事件即可.

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

            }

 

        } 

只需要在ondrop过程中获取相关拖放文件即可,这些可能通过一些html5的教程可以得到帮助。

这时候只需要针对选择的文件构建相关fileinfo对象,并调用上传方法即可.

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

                }

            }

        } 

通过uploadprocess事件对上传文件进度信息进行一个设置更新

function onuploadprocess(file) {

            $('#p_' + file.id).progressbar({ value: (file.pageindex / file.pages) * 100,

                text: file.filename + '[' + file.uploadbytes + '/' + file.size + ']'

            });

        } 

c#服务端

借助于beetle对websocket的支持对应服务端的实现就非常简单了

/// <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";

        }

    } 

服务端方法有两个一个是上传文件请求,和一个上传文件块接收方法.

总结

只需要以上简单的代码就能实现多文件同时上传功能,在这采用json来处理上传的信息,所以文件流要进行一个base64的编码处理,由于websocket浏览提交的数据一般都有mask处理再加上base64那损耗相对来说比较重,实际上websocket有提供流的数据包格式(arraybuffer);当然这种处理在操作上就没有json来得方便简单.

下载代码:websocketupload.rar  

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。