当前位置: 移动技术网 > IT编程>开发语言>.net > 30分钟玩转Net MVC 基于WebUploader的大文件分片上传、断网续传、秒传(文末附带demo下载)

30分钟玩转Net MVC 基于WebUploader的大文件分片上传、断网续传、秒传(文末附带demo下载)

2019年02月22日  | 移动技术网IT编程  | 我要评论

教学课件,四人打麻将,借枪迅雷下载

现在的项目开发基本上都用到了上传文件功能,或图片,或文档,或视频。我们常用的常规上传已经能够满足当前要求了,


 

然而有时会出现如下问题:

  1. 文件过大(比如1g以上),超出服务端的请求大小限制;
  2. 请求时间过长,请求超时;
  3. 传输中断,必须重新上传导致前功尽弃;
  4. 设置了webconfig和iis后还是不能上传成功;
  5. 不想使用ftp,只想用http。

 

我们这里只讲分片上传,至于断网续传和秒传已经写好demo,下载路径放在文末,有兴趣的可以下载下来自己玩玩。

分片上传demo下载地址:https://pan.baidu.com/s/1osgyv2qyztmtniimqkckvw 提取码:ie57

分片上传、断网续传、秒传demo下载地址:https://pan.baidu.com/s/1tuvgr6qucklmfjzgaql5vg 提取码:aej4

http的网络请求中本身就已经具备了分片上传功能,那么什么是分片上传?我们来看看:


 

分片上传原理

片上传支持将一个文件切割为一系列特定大小的数据片,分别将这些小数据片上传到服务端,全部上传完后再在服务端将这些数据片合并成为一个资源。

分片上传引入了两个概念:(block)和(chunk)。每个由一到多个组成,而一个资源则由一到多个组成。他们之间的关系可以用下图表述:

是上传过程中作为临时存储的单位。服务端会以约七天为单位的周期清除上传后未被合并为块(文件)的数据片(块)。

与分片上传相关的 api 有:创建块(mkblk)、上传片(bput)、创建文件(mkfile)。一个完整的分片上传流程可用下图表示:

其中的关键点如下:

将待上传的文件按预定义块大小切分为若干个块(每块大小不大于 4mb:块的大小可以自定义)。如果这个文件小于 4mb,就只有一个块。

将每个块再按预定义的片大小切分为若干个片,先在服务端创建一个相应块(通过调用mkblk,并带上第一个片的内容),然后再循环将所有剩下的片全部上传(通过调用bput,从而完成一个块的上传)

在所有块上传完成后,通过调用mkfile将这些上传完成的块信息再严格的按顺序组装出一个逻辑资源的元信息,从而完成整个资源的分片上传过程。


 在这个理论基础上,结合webuploade插件(百度上传插件)和net mvc进行demo编写,老规矩,demo在文末,可以下载。

我们看一下效果图:

分片上传:

      上传中(图一)

         

      上传成功(图二)

 


 分片、断网(暂停)、秒传:

 

上传中(图一)

上传成功(图二)


 

代码展示:

下载webuploader插件后引入项目中,

主要引用文件:

<script src="~/scripts/jquery-1.10.2.min.js"></script>
<link href="~/content/webuploader.css" rel="stylesheet" />
<script src="~/scripts/webuploader.js"></script>
<script src="~/scripts/bootstrap.min.js"></script>

前端完整代码:

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
<script src="~/scripts/jquery-1.10.2.min.js"></script>
<link href="~/content/webuploader.css" rel="stylesheet" />
<script src="~/scripts/webuploader.js"></script>
<script src="~/scripts/bootstrap.min.js"></script>
<div id="uploader" class="wu-example">
    <!--用来存放文件信息-->
    <div id="thelist" class="uploader-list"></div>
    <div class="btns">
        <div id="picker">选择文件</div>
        <input id="ctlbtn" type="button" value="开始上传" class="btn btn-default" />
    </div>
</div>
    <table width="50%" border="1" class="filelist_parent">
        <thead>
            <tr style="background-color:#dadada">
                <th>文件名称</th>
                <th>类型</th>
                <th>大小</th>
                <th>进度</th>
                <th>说明</th>
            </tr>
        </thead>

        <tbody class="filelist">
          
        </tbody>

    </table>
</body>
</html>
<script>
    var applicationpath = window.applicationpath === "" ? "" : window.applicationpath || "../../";
    var guid = webuploader.base.guid();//一个guid
    
    $(function () {
        var $ = jquery;
        var $list = $('#thelist');
        var uploader = webuploader.create({

            // 选完文件后,是否自动上传。
            auto: false,
            // swf文件路径
            swf: applicationpath + '../content/uploader.swf',

            // 文件接收服务端。
            server: applicationpath + 'home/upload',

            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建,可能是input元素,也可能是flash.
            pick: '#picker',

            chunked: true,//开始分片上传
            chunksize: 2048000,//每一片的大小
            formdata: {
                guid: guid //自定义参数,待会儿解释
            },

            // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
            resize: false
        });
        // 当有文件被添加进队列的时候
        uploader.on('filequeued', function (file) {
            $list.append('<div id="' + file.id + '" class="item">' +
                '<h4 class="info">' + file.name + '</h4>' +
                '<p class="state">等待上传...</p>' +
                '</div>');

            var name = file.name;    //文件名
            var type = filetype(file.name);    //文件类型,获取的是文件的后缀
            var volume = bytestosize(file.size);    //文件大小格式化


            var otr = $("<tr></tr>");
            var str = '<td><cite title="' + name + '">' + name + '</cite></td>';
            str += '<td>' + type + '</td>';
            str += '<td>' + volume + '</td>';
            str += '<td id="jintutiao">';
            str += '<span id="baifenbi"></span>0%';
            str += '</td>';
            str += '<td id="uploding">等待上传</td>';
            $(".filelist").html(str)
        });
        var aa = 1;
        // 文件上传过程中创建进度条实时显示。
        uploader.on('uploadprogress', function (file, percentage) {
            var $li = $('#' + file.id),
                $percent = $li.find('.progress .progress-bar');

            // 避免重复创建
            if (!$percent.length) {
                $percent = $('<div class="progress progress-striped active">' +
                    '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                    '</div>' +
                    '</div>').appendto($li).find('.progress-bar');
            }

            $li.find('p.state').text('上传中');
            $("#uploding").html("上传中");
            $percent.css('width', percentage * 100 + '%');
            if (percentage == 1)
            {
                aa++;
            }
            if (aa<=2)
            {
                var shuzi=percentage * 100;
                $("#baifenbi").html(shuzi.tofixed(2));
            }
        });

        // 文件上传成功,给item添加成功class, 用样式标记上传成功。
        uploader.on('uploadsuccess', function (file, response) {
            $('#' + file.id).find('p.state').text('已上传');
            $.post('home/merge', { guid: guid, filename: file.name }, function (data) {
                $("#uploader .state").html("上传成功...");
                $("#uploding").html("上传成功");
            });
        });

        // 文件上传失败,显示上传出错。
        uploader.on('uploaderror', function (file) {
            $('#' + file.id).find('p.state').text('上传出错');
        });

        // 完成上传完了,成功或者失败,先删除进度条。
        uploader.on('uploadcomplete', function (file) {
            $('#' + file.id).find('.progress').fadeout();
        });

        //所有文件上传完毕
        uploader.on("uploadfinished", function () {
            //提交表单
        });
        //开始上传
        $("#ctlbtn").click(function () {
            uploader.upload();
        });
    });

    //字节大小转换,参数为b
    function bytestosize(bytes) {
        var sizes = ['bytes', 'kb', 'mb', 'g'];
        if (bytes == 0) return 'n/a';
        var i = parseint(math.floor(math.log(bytes) / math.log(1024)));
        return (bytes / math.pow(1024, i)).tofixed(1) + ' ' + sizes[i];
    };

    //通过文件名,返回文件的后缀名
    function filetype(name) {
        var namearr = name.split(".");
        return namearr[namearr.length - 1].tolowercase();
    }
</script>

后端控制器完整代码展示:

using system;
using system.collections.generic;
using system.io;
using system.linq;
using system.web;
using system.web.mvc;

namespace bigfileuploader.controllers
{
    public class homecontroller : controller
    {#region 文件上传
        [httppost]
        public actionresult upload()
        {
            string filename = request["name"];
            string filerelname = filename.substring(0, filename.lastindexof('.'));//设置临时存放文件夹名称
            int index = convert.toint32(request["chunk"]);//当前分块序号
            var guid = request["guid"];//前端传来的guid号
            var dir = server.mappath("~/upload");//文件上传目录
            dir = path.combine(dir, filerelname);//临时保存分块的目录
            if (!system.io.directory.exists(dir))
                system.io.directory.createdirectory(dir);
            string filepath = path.combine(dir, index.tostring());//分块文件名为索引名,更严谨一些可以加上是否存在的判断,防止多线程时并发冲突
            var data = request.files["file"];//表单中取得分块文件
            string extension = data.filename.substring(data.filename.lastindexof(".") + 1,
                (data.filename.length - data.filename.lastindexof(".") - 1));//获取文件扩展名
            //if (data != null)//为null可能是暂停的那一瞬间
            //{
            data.saveas(filepath + filename);
            //}
            return json(new { erron = 0 });//demo,随便返回了个值,请勿参考
        }
        public actionresult merge()
        {
            var guid = request["guid"];//guid
            var uploaddir = server.mappath("~/upload");//upload 文件夹
            var filename = request["filename"];//文件名
            string filerelname = filename.substring(0, filename.lastindexof('.'));
            var dir = path.combine(uploaddir, filerelname);//临时文件夹          
            var files = system.io.directory.getfiles(dir);//获得下面的所有文件
            var finalpath = path.combine(uploaddir, filename);//最终的文件名(demo中保存的是它上传时候的文件名,实际操作肯定不能这样)
            var fs = new filestream(finalpath, filemode.create);
            foreach (var part in files.orderby(x => x.length).thenby(x => x))//排一下序,保证从0-n write
            {
                var bytes = system.io.file.readallbytes(part);
                fs.write(bytes, 0, bytes.length);
                bytes = null;
                system.io.file.delete(part);//删除分块
            }
            fs.flush();
            fs.close();
            system.io.directory.delete(dir);//删除文件夹
            return json(new { error = 0 });//随便返回个值,实际中根据需要返回
        }
        #endregion
    }
}

 


 

总结:

以上说的是分片上传的demo,断网续传和秒传在下面,大家下载下来玩哇,个人感觉蛮不错的。
我一直都主张功能点先写demo,有了成功的demo后引入项目中,demo可以存储起来做知识储备,保不定哪天又用到了。

大家感觉小编搞得不错话关注一波,后续还有很多干货在等着你呢^_^

分片上传demo下载地址:https://pan.baidu.com/s/1osgyv2qyztmtniimqkckvw 提取码:ie57

分片上传、断网续传、秒传demo下载地址:https://pan.baidu.com/s/1tuvgr6qucklmfjzgaql5vg 提取码:aej4

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网