webuploader 快速应用(C#)

百度的WebUploader前端插件作为目前比较好用且免费的附件上传工具,利用了断点续传特点实现了大文件上传功能,其更好的兼容性与界面效果完全可以替换掉IE的activex 上传控件。许多人或许还不知道怎么使用,下面的详细介绍可帮助开发者快速使用。

webuploader 官方下载地址:https://fex.baidu.com/webuploader/download.html

用vs新建项目WebUploaderDemo

引入webuploader

编写一般处理程序代码

  1     /// <summary>
  2     /// Upload 的摘要说明
  3     /// </summary>
  4     public class Upload : IHttpHandler
  5     {
  6         const string path = "/upfiles/";//上传目录
  7         const string tempPath = "/upfiles/temp/";//上传临时目录
  8 
  9         public void ProcessRequest(HttpContext context)
 10         {
 11             context.Response.ContentType = "text/plain";
 12             //如果进行了分片
 13             if (context.Request.Form.AllKeys.Any(m => m == "chunk"))
 14             {
 15                 //取得chunk和chunks
 16                 int chunk = Convert.ToInt32(context.Request.Form["chunk"]);//当前分片在上传分片中的顺序(从0开始)
 17                 int chunks = Convert.ToInt32(context.Request.Form["chunks"]);//总分片数
 18 
 19                 if (string.IsNullOrEmpty(context.Request["guid"]))
 20                     throw new Exception("[guid]不能为空");
 21 
 22                 //根据GUID创建用该GUID命名的临时文件夹
 23                 string folder = context.Server.MapPath(tempPath + context.Request["guid"] + "/");
 24                 string tempFile = folder + chunk;
 25 
 26                 //建立临时传输文件夹
 27                 if (!Directory.Exists(Path.GetDirectoryName(folder)))
 28                 {
 29                     Directory.CreateDirectory(folder);
 30                 }
 31 
 32                 FileStream addFile = new FileStream(tempFile, FileMode.Append, FileAccess.Write);
 33                 BinaryWriter AddWriter = new BinaryWriter(addFile);
 34                 //获得上传的分片数据流
 35                 HttpPostedFile file = context.Request.Files[0];
 36                 Stream stream = file.InputStream;
 37 
 38                 BinaryReader TempReader = new BinaryReader(stream);
 39                 //将上传的分片追加到临时文件末尾
 40                 AddWriter.Write(TempReader.ReadBytes((int)stream.Length));
 41                 //关闭BinaryReader文件阅读器
 42                 TempReader.Close();
 43                 stream.Close();
 44                 AddWriter.Close();
 45                 addFile.Close();
 46 
 47                 TempReader.Dispose();
 48                 stream.Dispose();
 49                 AddWriter.Dispose();
 50                 addFile.Dispose();
 51                 string filePath = "";
 52                 if (chunk == chunks - 1)
 53                 {
 54                     filePath = path + DateTime.Now.ToString("yyyy/MM/") + Guid.NewGuid() + Path.GetExtension(file.FileName);//合并后的文件
 55                     ProcessRequest(folder, context.Server.MapPath(filePath));
 56                 }
 57                 context.Response.Write("{\"chunked\" : true, \"hasError\" : false, \"filePath\" : \"" + filePath + "\"}");
 58             }
 59             else//没有分片直接保存
 60             {
 61                 string filePath = path + DateTime.Now.ToString("yyyy/MM/") + Guid.NewGuid() + Path.GetExtension(context.Request.Files[0].FileName);//合并后的文件
 62                 context.Request.Files[0].SaveAs(context.Server.MapPath(filePath));
 63                 context.Response.Write("{\"chunked\" : true, \"hasError\" : false, \"filePath\" : \"" + filePath + "\"}");
 64             }
 65         }
 66         /// <summary>
 67         /// 合并文件
 68         /// </summary>
 69         /// <param name="sourcePath">源数据文件夹</param>
 70         /// <param name="filePath">合并后的文件</param>
 71         private void ProcessRequest(string sourcePath, string filePath)
 72         {
 73             if (!Directory.Exists(Path.GetDirectoryName(filePath)))
 74             {
 75                 Directory.CreateDirectory(Path.GetDirectoryName(filePath));
 76             }
 77             DirectoryInfo dicInfo = new DirectoryInfo(sourcePath);
 78             if (Directory.Exists(Path.GetDirectoryName(sourcePath)))
 79             {
 80                 FileInfo[] files = dicInfo.GetFiles();
 81                 foreach (FileInfo file in files.OrderBy(f => int.Parse(f.Name)))
 82                 {
 83                     FileStream addFile = new FileStream(filePath, FileMode.Append, FileAccess.Write);
 84                     BinaryWriter AddWriter = new BinaryWriter(addFile);
 85 
 86                     //获得上传的分片数据流
 87                     Stream stream = file.Open(FileMode.Open);
 88                     BinaryReader TempReader = new BinaryReader(stream);
 89                     //将上传的分片追加到临时文件末尾
 90                     AddWriter.Write(TempReader.ReadBytes((int)stream.Length));
 91                     //关闭BinaryReader文件阅读器
 92                     TempReader.Close();
 93                     stream.Close();
 94                     AddWriter.Close();
 95                     addFile.Close();
 96 
 97                     TempReader.Dispose();
 98                     stream.Dispose();
 99                     AddWriter.Dispose();
100                     addFile.Dispose();
101                 }
102                 Directory.Delete(sourcePath, true);
103             }
104         }
105 
106         /// <summary>
107         /// 删除文件夹
108         /// </summary>
109         /// <param name="strPath"></param>
110         private static void DeleteFolder(string strPath)
111         {
112             if (Directory.GetDirectories(strPath).Length > 0)
113             {
114                 foreach (string fl in Directory.GetDirectories(strPath))
115                 {
116                     Directory.Delete(fl, true);
117                 }
118             }
119             //删除这个目录下的所有文件
120             if (Directory.GetFiles(strPath).Length > 0)
121             {
122                 foreach (string f in Directory.GetFiles(strPath))
123                 {
124                     System.IO.File.Delete(f);
125                 }
126             }
127         }

编写前端代码

  1 <div id="uploadfile" class="updown">
  2         <div class="title">
  3             <label>上传</label>
  4         </div>
  5         <div id="uploader" class="wu-example">
  6             <div class="btns">
  7                 <div id="pickerfile">选择文件</div>
  8                 <button id="ctlBtnUp" class="btn-default">开始上传</button>
  9             </div>            <!--用来存放文件信息-->
 10             <div id="thelistupload" class="uploader-list"></div>
 11         </div>
 12     </div>
 13     <script type="text/javascript">
 14         var uploadindex = 0;
 15         function UploadInit() {
 16             uploadindex = 1;
 17             var GUID = WebUploader.Base.guid(); //当前页面是生成的GUID作为标示
 18             var $list = $("#thelistupload");
 19             var uploader = WebUploader.create({
 20 
 21                 // swf文件路径
 22                 swf: '/plugins/webuploader-0.1.5/Uploader.swf',
 23 
 24                 // 文件接收服务端。
 25                 server: "/ashx/Upload.ashx",
 26 
 27                 // 选择文件的按钮。可选。
 28                 // 内部根据当前运行是创建,可能是input元素,也可能是flash.
 29                 pick: '#pickerfile',
 30                 formData: { guid: GUID },
 31                 // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
 32                 resize: false,
 33                 //切片
 34                 chunked: true,
 35                 //每片的大小,C#接收文件也有默认大小,也可以自己在C#中修改
 36                 chunkSize: 2 * 1024 * 1024,
 37                 threads: 1,
 38                 accept: {
 39                     title: 'File',
 40                     extensions: '*',
 41                     mimeTypes: '*'
 42                 }
 43             });
 44             // 当有文件被添加进队列的时候
 45             uploader.on('fileQueued', function (file) {
 46                 console.log(file);
 47                 $list.append('<div id="' + file.id + '" class="item">' +
 48                     '<h4 class="info">' + file.name + '' + getfilesize(file.size) + ')</h4>' +
 49                     '<p class="state">等待上传...</p>' +
 50                     '</div>');
 51 
 52             });
 53             uploader.on('beforeFileQueued', function (file) {
 54                 $list.empty();
 55                 uploader.reset();
 56             });
 57             // 文件上传过程中创建进度条实时显示。
 58             uploader.on('uploadProgress', function (file, percentage) {
 59                 var $li = $('#' + file.id);
 60                 $li.find('p.state').text('上传中(' + (percentage * 100).toFixed(2) + '%)');
 61             });
 62             uploader.on('uploadSuccess', function (file) {
 63                 console.log("uploadSuccess:");
 64                 console.log(file);
 65                 $('#' + file.id).find('p.state').text('已上传');
 66             });
 67 
 68             uploader.on('uploadError', function (file, code) {
 69                 $('#' + file.id).find('p.state').text('上传出错');
 70             });
 71 
 72             uploader.on('uploadComplete', function (file) {
 73                 $('#' + file.id).find('.progress').fadeOut();
 74             });
 75 
 76             uploader.on('uploadAccept', function (file, response) {
 77                 console.log("uploadAccept:");
 78                 console.log(file);
 79                 console.log(response);
 80                 if (response['hasError'] != false) {
 81                     // 通过return false来告诉组件,此文件上传有错。
 82 
 83                     return false;
 84                 }
 85                 else {
 86                     return true;
 87                 }
 88             });
 89             $("#ctlBtnUp").on('click', function () {
 90                 uploader.upload();
 91             });
 92         }
 93 
 94         if (uploadindex === 0) {
 95             UploadInit();
 96         }
 97 
 98 
 99         // 计算文件大小函数(保留两位小数),Size为字节大小
100         // size:初始文件大小
101         function getfilesize(size) {
102             if (!size)
103                 return "";
104 
105             var num = 1024.00; //byte
106             if (size < num)
107                 return size + "B";
108             if (size < Math.pow(num, 2))
109                 return (size / num).toFixed(2) + "K"; //kb
110             if (size < Math.pow(num, 3))
111                 return (size / Math.pow(num, 2)).toFixed(2) + "M"; //M
112             if (size < Math.pow(num, 4))
113                 return (size / Math.pow(num, 3)).toFixed(2) + "G"; //G
114             return (size / Math.pow(num, 4)).toFixed(2) + "T"; //T
115         }
116 
117     </script>

最终效果:

 demo下载地址:

链接:https://pan.baidu.com/s/1bSMK7EZ6cdJMDeHMuFkYBA
提取码:i4cn 

转载于:https://www.cnblogs.com/xiaodongxiaoji/p/11150590.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值