• WEB版一次选择多个文件进行批量上传(WebUploader)的解决方案


     最近在学习百度的开源上传组件WebUploader,写了一些示例以记录。WebUploader的缺点是没有一个比较好的现成的界面,这个界面需要自己去实现。自由度高了一些。

           WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件。在现代的浏览器里面能充分发挥HTML5的优势,同时又不摒弃主流IE浏览器,沿用原来的FLASH运行时,兼容IE6+,iOS 6+, android 4+。两套运行时,同样的调用方式,可供用户任意选用。

    关于WebUploader的功能说明:

    分片、并发

    分片与并发结合,将一个大文件分割成多块,并发上传,极大地提高大文件的上传速度。

    当网络问题导致传输错误时,只需要重传出错分片,而不是整个文件。另外分片传输能够更加实时的跟踪上传进度。

    预览、压缩

    支持常用图片格式jpg,jpeg,gif,bmp,png预览与压缩,节省网络数据传输。

    解析jpeg中的meta信息,对于各种orientation做了正确的处理,同时压缩后上传保留图片的所有原始meta数据。

    多途径添加文件

    支持文件多选,类型过滤,拖拽(文件&文件夹),图片粘贴功能。

    粘贴功能主要体现在当有图片数据在剪切板中时(截屏工具如QQ(Ctrl + ALT + A), 网页中右击图片点击复制),Ctrl + V便可添加此图片文件。

    HTML5 & FLASH

    兼容主流浏览器,接口一致,实现了两套运行时支持,用户无需关心内部用了什么内核。

    同时Flash部分没有做任何UI相关的工作,方便不关心flash的用户扩展和自定义业务需求。

    MD5秒传

    当文件体积大、量比较多时,支持上传前做文件md5值验证,一致则可直接跳过。

    如果服务端与前端统一修改算法,取段md5,可大大提升验证性能,耗时在20ms左右。

    易扩展、可拆分

    采用可拆分机制, 将各个功能独立成了小组件,可自由搭配。

    采用AMD规范组织代码,清晰明了,方便高级玩家扩展。


    一: 下面就是利用WebUploader组件,让客户一次选择多个文件,然后将选择的文件上传到服务器的批量文件解决方案。

    让我们先来看看客户端的界面效果图。(多选文件,批量上传,上传进度显示)

    1) 显示界面:

     

    图1

    2) 进行多文件选择:

     

                                               图2

     

    3) 上传进度显示

     

                                           图3

     

                           图4

    说明:见上图WebUploader默认是3个线程一起并发上传文件。如果需要增加并发数,或是减少并发数。可以修改threads属性,这个属性就是允许的最大上传并发数。

     

    3) 上传成功显示

                           图5


    二:具体的代码与操作步骤:

    第一步,要完成下面的示例,必须先准备好WebUploader组件。
    1) WebUploader:大家可以访问WebUploader官方网站:http://fex.baidu.com/webuploader/download.html,在这个网站上可以下载到组件与demo。

    第二步,这个示例的目录结构如图:
    1.主要目录结构

     

    2. 此示例中用到的js脚本文件与css文件。

      

    第三步,前台部分准备客户操作的WEB界面,如下[WebUploaderFileByBaidu2.aspx、UploaderFileByBaidu.ashx]

    1)  前台客户端代码,其中WebUploaderFileByBaidu2.aspx的代码如下,WebUploaderFileByBaidu2.aspx.cs文件中只使用默认的代码,不用添加任何代码。

     Html代码
     

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebUploaderFileByBaidu2.aspx.cs" Inherits="WebApplication1.WebUploaderFileByBaidu2" %>
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>WebUploader文件上传示例</title>
        <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>   
          <link href="Scripts/webuploader/webuploader.css" rel="stylesheet" />
        <script type="text/javascript" src="Scripts/webuploader/webuploader.min.js"></script>
        <link href="https://cdn.bootcss.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"/>   
        <link href="Scripts/style.css" rel="stylesheet" />
        <link href="Scripts/demo.css" rel="stylesheet" />
        <link href="Scripts/font-awesome.css" rel="stylesheet" /> 
         <script type="text/javascript">
             var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../../";
             // 文件上传
             jQuery(function () {
                 var $ = jQuery,
                     $list = $('#fileList'),
                     $btn = $('#ctlBtn'),
                     state = 'pending',
                     uploader;
                 uploader = WebUploader.create({
                     // 不压缩image
                     resize: false, 
                     // swf文件路径
                     swf: applicationPath + 'Script/webuploader/Uploader.swf',
                     // 文件接收服务端。
                     server: 'UploaderFileByBaidu.ashx',
                     // 选择文件的按钮。可选。
                     // 内部根据当前运行是创建,可能是input元素,也可能是flash.
                     pick: '#picker'
                 }); 
                 // 当有文件添加进来的时候
                 uploader.on('fileQueued', function (file) {
                     $list.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=" 0%">' +
                           '</div>' +
                         '</div>').appendTo($li).find('.progress-bar');
                     }
                     $li.find('p.state').text('上传中');
                     $percent.css('width', percentage * 100 + '%');
                 });
                 uploader.on('uploadSuccess', function (file) {
                     $('#' + file.id).find('p.state').text('已上传');
                 });
                 uploader.on('uploadError', function (file) {
                     $('#' + file.id).find('p.state').text('上传出错');
                 });
                 uploader.on('uploadComplete', function (file) {
                     $('#' + file.id).find('.progress').fadeOut();
                 });
                 uploader.on('all', function (type) {
                     if (type === 'startUpload') {
                         state = 'uploading';
                     } else if (type === 'stopUpload') {
                         state = 'paused';
                     } else if (type === 'uploadFinished') {
                         state = 'done';
                     }
                     if (state === 'uploading') {
                         $btn.text('暂停上传');
                     } else {
                         $btn.text('开始上传');
                     }
                 });
                 $btn.on('click', function () {
                     if (state === 'uploading') {
                         uploader.stop();
                     } else {
                         uploader.upload();
                     }
                 });
             });
        </script>
    </head>
    <body>
        <div  class="container-fluid">
            <div class="col-md-10">
            <div class="row">文件上传示例:</div>
             <div class="row">
      <div id="uploader" class="wu-example">
        <!--用来存放文件信息-->
        <div id="fileList" class="uploader-list"></div>
        <div class="btns">
            <div id="picker" class="btn btn-primary">选择文件</div>    
        </div>
    </div>
                 </div>
              <div class="row">
        </div>
            <div class="row">  <button id="ctlBtn" class="btn btn-default">开始上传</button></div>
        </div>
        <div>
        </div>
        </div>
    </body>
    </html>

    以上代码最后的显示结果如下图:

     

                                          图8.

    2) 接收前端用户上传的文件,并把文件保存到指定目录中。UploaderFileByBaidu.ashx文件中使用默认的代码,不需要添加任何代码。UploaderFileByBaidu.ashx.cs文件的代码如下:  

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Web;
    namespace WebApplication1
    {
        /// <summary>
        /// UploaderFileByBaidu 的摘要说明
        /// </summary>
        public class UploaderFileByBaidu : IHttpHandler
        {
            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentEncoding = Encoding.UTF8;
                if (context.Request["REQUEST_METHOD"] == "OPTIONS")  
              {
                    context.Response.End();
                }
                SaveFile();
            }
            /// <summary>
            /// 文件保存操作
            /// </summary>
            /// <param name="basePath"></param>
            private void SaveFile(string basePath = "~/Upload/Images/")
            {
         
                 basePath = FileHelper.GetUploadPath();
                string Datedir = DateTime.Now.ToString("yy-MM-dd");
                string updir = basePath + "\" + Datedir;
                string extname = string.Empty;
                string fullname = string.Empty;
                string filename = string.Empty;     
                HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
                if (files.Count == 0)
                {
                    var result = "{"jsonrpc" : "2.0", "error" :  "保存失败","id" :  "id"}";
                    System.Web.HttpContext.Current.Response.Write(result);
                }
                if (!Directory.Exists(updir))
                    Directory.CreateDirectory(updir);
                var suffix = files[0].ContentType.Split('/');
                var _suffix = suffix[1].Equals("jpeg", StringComparison.CurrentCultureIgnoreCase) ? "" : suffix[1];
                var _temp = System.Web.HttpContext.Current.Request["name"];
                if (!string.IsNullOrEmpty(_temp))
                {
                    filename = _temp;
                }
                else
                {
                    Random rand = new Random(24 * (int)DateTime.Now.Ticks);
                    filename = rand.Next() + "." + _suffix;
                } 
                 fullname = string.Format("{0}\{1}",updir , filename);
                files[0].SaveAs(fullname);
                var _result = "{"jsonrpc" : "2.0", "result" : null, "id" : "" + filename + ""}";
                System.Web.HttpContext.Current.Response.Write(_result);
            } 
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }

      第四步:文件辅助类

    /// <summary>
    ///FileHelper 的摘要说明
    /// </summary>
    public class FileHelper
    {
        public FileHelper()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }
        /// <summary>
        /// 获取上传目录
        /// </summary>
        /// <returns></returns>
         public static string GetUploadPath()
            {
              string path = HttpContext.Current.Server.MapPath("~/");
              string dirname = GetDirName();
              string uploadDir = path + "\" + dirname;
              CreateDir(uploadDir);
              return uploadDir;
            }
        /// <summary>
        /// 获取临时目录
        /// </summary>
        /// <returns></returns>
         public static string GetTempPath()
         {
             string path = HttpContext.Current.Server.MapPath("~/");
             string dirname = GetTempDirName();
             string uploadDir = path + "\" + dirname;
             CreateDir(uploadDir);
             return uploadDir;
         }
            private static string GetDirName()
            {
                return System.Configuration.ConfigurationManager.AppSettings["uploaddir"];
            }
            private static string GetTempDirName()
            {
                return System.Configuration.ConfigurationManager.AppSettings["tempdir"];
            }
        public static void CreateDir(string path)
            {
                    if (!System.IO.Directory.Exists(path))
                    {                  
                        System.IO.Directory.CreateDirectory(path);
                    }
            }
    }

     第五步,Web.config文件配置信息。

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->   
      </configSections>
      <appSettings>
        <add key="uploaddir" value="upload" />
        <add key="tempdir" value="temp" />
      </appSettings>
      <system.web>
        <compilation debug="true" targetFramework="4.0" />
     
        <authentication mode="Windows" />
         <httpRuntime maxRequestLength="2147483647" appRequestQueueLimit="1200" executionTimeout="1200"/>
        <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" />
      </system.web>
        <system.webServer>
        <security>
          <requestFiltering >
            <requestLimits maxAllowedContentLength="2147483647" ></requestLimits>
          </requestFiltering>
        </security>
      </system.webServer>
    </configuration>

    第六步,在进行上传之后,文件保存在对应的日期目录下。如下图。

    到这,DEMO下载地址:https://dwz.cn/fgXtRtnu


  • 相关阅读:
    hdu5833----高斯消元
    高斯消元模板
    hdu4462--曼哈顿距离
    卡特兰数应用
    poj3070矩阵快速幂求斐波那契数列
    poj1042
    poj1328
    mvc 请求处理管道
    sql update 代替游标写法
    sql 表字段模糊连接
  • 原文地址:https://www.cnblogs.com/xproer/p/10740114.html
Copyright © 2020-2023  润新知