C# jquery webuploader基础用法+分片上传

35 篇文章 2 订阅
本文介绍了一个使用WebUploader实现的HTML页面文件上传功能,包括前端HTML结构、JavaScript配置以及WebUploader的初始化设置。文件上传过程中,前端通过监听事件处理进度、成功、错误和完成状态。后台使用ASHX处理程序接收分片上传的文件,通过静态变量保存上传信息,并进行文件拼接。该示例特别关注分片上传的管理和进度显示。
摘要由CSDN通过智能技术生成

先画html页面:

<div id="uploader" class="wu-example">
   <div id="thelist" class="uploadr-list"></div>
    <div class="btns">
        <div id="picker">选择文件</div>
        <button id="ctilBtn" class="btn btn-default">上传</button>
    </div>
</div>

js:
初始化webuploader:

var uploader = WebUploader.create({

	// swf文件路径
	 swf: "../node_modules/webuploader/dist/Uploader.swf",
	
	 // 文件接收服务端。
	 server: serverURL + 'Helper/HandlerHelper.ashx',
	 // 选择文件的按钮。可选。
	 // 内部根据当前运行是创建,可能是input元素,也可能是flash.
	 pick: { id: '#picker', multiple: false },
	 //fileVal:'Files',    //参数名称
	 chunked: true,
	 // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
	 resize: false,
	 fileSingleSizeLimit: 4572213932, //大小限制,默认是undefined
	 chunkSize: 180 * 1024,	//分片大小
	 threads: 1,	//上传并发数。允许同时最大上传进程数。
	 duplicate: false,	//可重复上传
	 chunkRetry: true,
	 formData: {
	     'subjectID': getUrlParam('subjectID'),	//不需要参数可以不传
	 }
});

要做一些其他处理的话,可以写在js里的监听事件里:

function listenForUpload(){
    $("#ctilBtn").on('click', function () {
            uploader.options.formData.smallSubjectID = $('#smallTitle').val(),
                uploader.options.formData.folderType = $('#folderType').val(),
            uploader.options.formData.mainContent = $('#mainContent').text()
            uploader.upload();
    });
     // 当有文件被添加进队列的时候
    uploader.on('fileQueued', function (file) {
        //if ($('#thelist').text() != '') {
        //    var oldFileID = $('#thelist').firstChild.id;
        //    uploader.removeFile(oldFileID, true);
        //    $('#thelist').empty();
        //}
        $('#thelist').html('');
        $('#thelist').append( '<div id="' + file.id + '" class="item">' +
            '<h4 class="info">' + file.name + '</h4>' +
            '<p class="state">等待上传...</p>' +
        '</div>' );
    });
    // 文件上传过程中创建进度条实时显示。
    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('上传中');

        $percent.css( 'width', percentage * 100 + '%' );
    });

    uploader.on('uploadSuccess', function (file,response) {
        $('#' + file.id).find('p.state').text('已上传');
        uploadID.push(response);
    });
    
    uploader.on( 'uploadError', function( file ) {
        $( '#'+file.id ).find('p.state').text('上传出错');
    });
    
    uploader.on( 'uploadComplete', function( file ) {
        $( '#'+file.id ).find('.progress').fadeOut();
    });
}

后台用一般处理程序ashx来接收文件
HandlerHelper.ashx:
分片上传时,这个方法会调用很多次,如果有一些需要保存的信息,可以写在外面的静态变量里,就不会每次都置初始值了

static string fileName = "";
static int dbID;
public void ProcessRequest(HttpContext context)
        {
            context.Response.AddHeader("Access-Control-Allow-Origin", "*");
            context.Response.ContentType = "text/plain";
            HttpPostedFile file = context.Request.Files[0];

            int chunks = 0, chunk = 0;
            if (context.Request.Form["chunks"] != null)
            {
                chunks = int.Parse(context.Request.Form["chunks"]);
                chunk = int.Parse(context.Request.Form["chunk"]);
                //这个chunk可以记录当前分片是第几次
            }
            if (chunks != 0)
            {
                string extension = System.IO.Path.GetExtension(file.FileName);
                //这个名字就随便建一个
                string fileTempPath = "fdsdfsdf/dfs"
                //第一次保存
                if (chunk == 0)
                {
                    if (!Directory.Exists(fileTempPath))
                    {
                        Directory.CreateDirectory(fileTempPath);
                    }
                    Random random = new Random();
                    string fileNameRandom = random.Next() + extension;
                    fileName = fileNameRandom;
                    fileTempPath += fileNameRandom;
                    //这个ID值是用来存表的,如果不需要ID值可以不存
                    dbID = AddfileToDB(file, fileNameRandom, fileTempPath);
                    context.Response.Write(dbID);
                    return;
                }
                //追加,这里就是第二次开始往后分片上传的地方
                using (FileStream addFile = new FileStream(fileTempPath+fileName, FileMode.Append, FileAccess.Write))
                {
                    BinaryWriter bWriter = new BinaryWriter(addFile);
                    Stream stream = file.InputStream;
                    BinaryReader tempReader = new BinaryReader(stream);
                    bWriter.Write(tempReader.ReadBytes((int)stream.Length));
                    tempReader.Close();
                    stream.Close();
                }
                //如果需要返回给前台,最好每次都返回,防止上传中途出错
                context.Response.Write(dbID);
            }
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值