当前位置: 首页 > news >正文

使用jQuery.FileUpload和Backload自定义控制器上传多个文件

当需要在控制器中处理除了文件的其他表单字段,执行控制器独有的业务逻辑......等等,这时候我们可以自定义控制器。 

  通过继承BackloadController

□ 思路

BackloadController的HandleRequestAsync()方法可以用来处理异步请求,通过继承BackloadController,子类也有了处理异步文件请求的能力。客户端方面,需要一个指向自定义控制器的初始化js文件。 

□ FileUploadDerivedController继承BackloadController

   1:      public class FileUploadDerivedController : BackloadController
   2:      {
   3:          public ActionResult Index()
   4:          {
   5:              return View();
   6:          }
   7:   
   8:          public async Task<ActionResult> FileHandler()
   9:          {
  10:              ActionResult result = await base.HandleRequestAsync();
  11:              return result;
  12:          }
  13:      }

 □ 创建一个指向自定义控制器的js文件main.js

   1:  $(function () {
   2:      'use strict';
   3:   
   4:      var fileUploadUrl = "/FileUploadDerived/FileHandler";
   5:   
   6:      // Initialize the jQuery File Upload widget:
   7:      $('#fileupload').fileupload({
   8:          url: fileUploadUrl,
   9:          acceptFileTypes: /(jpg)|(jpeg)|(png)|(gif)$/i // Allowed file types
  10:      });
  11:   
  12:      // Optional: Initial ajax request to load already existing files.
  13:      $.ajax({
  14:          url: fileUploadUrl,
  15:          dataType: 'json',
  16:          context: $('#fileupload')[0]
  17:      })
  18:      .done(function (result) {
  19:          $(this).fileupload('option', 'done')
  20:              .call(this, null, { result: result });
  21:          // Attach the Colorbox plugin to the image files to preview them in a modal window. Other file types (e.g. pdf) will show up in a 
  22:          // new browser window.
  23:          $(".files tr[data-type=image] a").colorbox();
  24:      });
  25:   
  26:   
  27:      // Initialize the jQuery ui theme switcher:
  28:      $('#theme-switcher').change(function () {
  29:          var theme = $('#theme');
  30:          theme.prop(
  31:              'href',
  32:              theme.prop('href').replace(
  33:                  /[\w\-]+\/jquery-ui.css/,
  34:                  $(this).val() + '/jquery-ui.css'
  35:              )
  36:          );
  37:      });
  38:  });
  39:   
  40:   
  41:  $("document").ready(function () {
  42:      // The Colorbox plugin needs to be informed on new uploaded files in the template in order to bind a handler to it. 
  43:      // There must be a little delay, because the fileuploaddone event is triggered before the new template item is created.
  44:      // A more elegant solution would be to use jQuery's delegated .on method, which automatically binds to the anchors in a
  45:      // newly created template item, and then call colorbox manually.
  46:      $('#fileupload').bind('fileuploaddone', function(e, data) {
  47:          setTimeout(function() { $(".files tr[data-type=image] a").colorbox() }, 1000);
  48:      });
  49:  });    
  50:   

□ 其中用到了colorbox插件

install-package colorbox

11

 □ FileUploadDerived/Index.cshtml视图

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

    <div>
        <!-- The file upload form used as target for the file upload widget -->
        <form id="fileupload" action="/Backload/UploadHandler" method="POST" enctype="multipart/form-data">
            <!-- Redirect browsers with JavaScript disabled to the origin page -->
            <noscript><input type="hidden" name="redirect" value="/"></noscript>
            <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
            <div class="row fileupload-buttonbar">
                <div class="span7">
                    <!-- The fileinput-button span is used to style the file input field as button -->
                    <span class="btn btn-success fileinput-button">
                        <i class="icon-plus icon-white"></i>
                        <span>添加文件...</span>
                        <input type="file" name="files[]" multiple>
                    </span>
                    <button type="submit" class="btn btn-primary start">
                        <i class="icon-upload icon-white"></i>
                        <span>开始上传</span>
                    </button>
                    <button type="reset" class="btn btn-warning cancel">
                        <i class="icon-ban-circle icon-white"></i>
                        <span>取消上传</span>
                    </button>
                    <button type="button" class="btn btn-danger delete">
                        <i class="icon-trash icon-white"></i>
                        <span>删除</span>
                    </button>
                    <input type="checkbox" class="toggle">
                    <!-- The loading indicator is shown during file processing -->
                    <span class="fileupload-loading"></span>
                </div>
                <!-- The global progress information -->
                <div class="span5 fileupload-progress fade">
                    <!-- The global progress bar -->
                    <div class="progress progress-success progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                        <div class="bar" style="width:0%;"></div>
                    </div>
                    <!-- The extended global progress information -->
                    <div class="progress-extended">&nbsp;</div>
                </div>
            </div>
            <!-- The table listing the files available for upload/download -->
            <table role="presentation" class="table table-striped"><tbody class="files" data-toggle="modal-gallery" data-target="#modal-gallery"></tbody></table>
        </form>  

        <!-- The template to display files available for upload -->
        <script id="template-upload" type="text/x-tmpl">
        {% for (var i=0, file; file=o.files[i]; i++) { %}
            <tr class="template-upload fade">
                <td>
                    <span class="preview"></span>
                </td>
                <td>
                    <p class="name">{%=file.name%}</p>
                    {% if (file.error) { %}
                        <div><span class="label label-important">Error</span> {%=file.error%}</div>
                    {% } %}
                </td>
                <td>
                    <p class="size">{%=o.formatFileSize(file.size)%}</p>
                    {% if (!o.files.error) { %}
                        <div class="progress progress-success progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="bar" style="width:0%;"></div></div>
                    {% } %}
                </td>
                <td>
                    {% if (!o.files.error && !i && !o.options.autoUpload) { %}
                        <button class="btn btn-primary start">
                            <i class="icon-upload icon-white"></i>
                            <span>Start</span>
                        </button>
                    {% } %}
                    {% if (!i) { %}
                        <button class="btn btn-warning cancel">
                            <i class="icon-ban-circle icon-white"></i>
                            <span>Cancel</span>
                        </button>
                    {% } %}
                </td>
            </tr>
        {% } %}
        </script>
        <!-- The template to display files available for download -->
        <script id="template-download" type="text/x-tmpl">
        {% for (var i=0, file; file=o.files[i]; i++) { %}
            <tr class="template-download fade">
                <td>
                    <span class="preview">
                        {% if (file.thumbnail_url) { %}
                            <a href="{%=file.url%}" title="{%=file.name%}" data-gallery="gallery" download="{%=file.name%}"><img src="{%=file.thumbnail_url%}"></a>
                        {% } %}
                    </span>
                </td>
                <td>
                    <p class="name">
                        <a href="{%=file.url%}" title="{%=file.name%}" data-gallery="{%=file.thumbnail_url&&'gallery'%}" download="{%=file.name%}">{%=file.name%}</a>
                    </p>
                    {% if (file.error) { %}
                        <div><span class="label label-important">Error</span> {%=file.error%}</div>
                    {% } %}
                </td>
                <td>
                    <span class="size">{%=o.formatFileSize(file.size)%}</span>
                </td>
                <td>
                    <button class="btn btn-danger delete" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}"{% if (file.delete_with_credentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
                        <i class="icon-trash icon-white"></i>
                        <span>Delete</span>
                    </button>
                    <input type="checkbox" name="delete" value="1" class="toggle">
                </td>
            </tr>
        {% } %}
        </script>      
    </div>


@section scripts
{
    @* <script src="~/Scripts/FileUpload/backload.demo.js"></script>*@
    <script src="~/Scripts/main.js"></script>
}

□ 在web.config中设置目的文件夹CustomerController

   1:  <configuration>
   2:    <configSections>
   3:      ...  
   4:    <section name="backload" type="Backload.Configuration.BackloadSection, Backload, Version=1.9.3.1, Culture=neutral, PublicKeyToken=02eaf42ab375d363" requirePermission="false" />
   5:    </configSections>
   6:    
   7:     <backload xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:name="urn:fileupload-schema" xsi:noNamespaceSchemaLocation="Web.FileUpload.xsd">
   8:      <fileSystem filesRoot="~/CustomerController" />
   9:    </backload>
  10:  </configuration>

□ 结果

上传界面:

12

 CustomerController文件夹:
13

 CustomerController文件夹内容:
14

  通过为FileUploadHandler的事件IncomingRequestStarted注册方法

□ 思路

为FileUploadHandler的事件IncomingRequestStarted注册方法,再让事件处理异步文件请求。客户端方面,需要一个指向自定义控制器的初始化js文件。

 □ FileUploadInstanceController

   1:     public class FileUploadInstanceController : Controller
   2:      {
   3:          public ActionResult Index()
   4:          {
   5:              return View();
   6:          }
   7:   
   8:          public async Task<ActionResult> FileHandler()
   9:          {
  10:              FileUploadHandler handler = new FileUploadHandler(Request, this);
  11:              handler.IncomingRequestStarted += handler_IncomingRequestStarted;
  12:              ActionResult result = await handler.HandleRequestAsync();
  13:              return result;
  14:          }
  15:   
  16:          void handler_IncomingRequestStarted(object sender, Backload.Eventing.Args.IncomingRequestEventArgs e)
  17:          {
  18:              //禁止添加操作
  19:              if (e.Context.HttpMethod == "PUT")
  20:              {
  21:                  e.Context.PipelineControl.ExecutePipeline = false;
  22:              }
  23:          }
  24:      }
  25:   

 □ 创建一个指向自定义控制器的js文件main.js

   1:  $(function () {
   2:      'use strict';
   3:   
   4:      var fileUploadUrl = "/FileUploadInstance/FileHandler";
   5:   
   6:   
   7:      // Initialize the jQuery File Upload widget:
   8:      $('#fileupload').fileupload({
   9:          url: fileUploadUrl,
  10:          acceptFileTypes: /(jpg)|(jpeg)|(png)|(gif)$/i // Allowed file types
  11:      });
  12:   
  13:      // Optional: Initial ajax request to load already existing files.
  14:      $.ajax({
  15:          url: fileUploadUrl,
  16:          dataType: 'json',
  17:          context: $('#fileupload')[0]
  18:      })
  19:      .done(function (result) {
  20:          $(this).fileupload('option', 'done')
  21:              .call(this, null, { result: result });
  22:          // Attach the Colorbox plugin to the image files to preview them in a modal window. Other file types (e.g. pdf) will show up in a 
  23:          // new browser window.
  24:          $(".files tr[data-type=image] a").colorbox();
  25:      });
  26:   
  27:   
  28:   
  29:      // Initialize the jQuery ui theme switcher:
  30:      $('#theme-switcher').change(function () {
  31:          var theme = $('#theme');
  32:          theme.prop(
  33:              'href',
  34:              theme.prop('href').replace(
  35:                  /[\w\-]+\/jquery-ui.css/,
  36:                  $(this).val() + '/jquery-ui.css'
  37:              )
  38:          );
  39:      });
  40:  });
  41:   
  42:   
  43:  $("document").ready(function () {
  44:      // The Colorbox plugin needs to be informed on new uploaded files in the template in order to bind a handler to it. 
  45:      // There must be a little delay, because the fileuploaddone event is triggered before the new template item is created.
  46:      // A more elegant solution would be to use jQuery's delegated .on method, which automatically binds to the anchors in a
  47:      // newly created template item, and then call colorbox manually.
  48:      $('#fileupload').bind('fileuploaddone', function(e, data) {
  49:          setTimeout(function() { $(".files tr[data-type=image] a").colorbox() }, 1000);
  50:      });
  51:  });    
  52:   

□ FileUploadInstance/Index.cshtml视图

同上

 □ 在web.config中设置目的文件夹FileUpload

   1:  <configuration>
   2:    <configSections>
   3:      ...  
   4:    <section name="backload" type="Backload.Configuration.BackloadSection, Backload, Version=1.9.3.1, Culture=neutral, PublicKeyToken=02eaf42ab375d363" requirePermission="false" />
   5:    </configSections>
   6:    
   7:     <backload xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:name="urn:fileupload-schema" xsi:noNamespaceSchemaLocation="Web.FileUpload.xsd">
   8:      <fileSystem filesRoot="~/FileUpload" />
   9:    </backload>
  10:  </configuration>

 

□ 结果

上传界面:

15

 FileUpload文件夹:
16

 FileUpload文件夹内容:
17

 

转载于:https://www.cnblogs.com/wangsai/p/4113303.html

相关文章:

  • 从零开始iOS8编程【HelloWorld】
  • 微软职位内部推荐-SDEII for Windows Phone Apps
  • 关于PCB 3D 模型的快速导入方法
  • FreeSWITCH在呼叫失败的情况下播放语音提示
  • STL容器的使用
  • Mysql索引类型 Normal,Unique,Full Text
  • Linux定时任务没有执行的总结
  • Hql 一种错误写法的分析
  • nginx 405 not allowed问题的解决
  • Mac 与 PC 键盘布局对比
  • oracle 创建视图、修改视图、删除视图、利用视图操作基本表
  • 什么是基准测试?
  • 文件系统,快存储,对象存储
  • 图的基本概念
  • MySQL主从复制、搭建、状态检查、中断排查及备库重做
  • JS中 map, filter, some, every, forEach, for in, for of 用法总结
  • 《深入 React 技术栈》
  • 「译」Node.js Streams 基础
  • 【402天】跃迁之路——程序员高效学习方法论探索系列(实验阶段159-2018.03.14)...
  • CentOS7简单部署NFS
  • eclipse(luna)创建web工程
  • java B2B2C 源码多租户电子商城系统-Kafka基本使用介绍
  • Octave 入门
  • Python十分钟制作属于你自己的个性logo
  • Sass Day-01
  • SpingCloudBus整合RabbitMQ
  • SQLServer之索引简介
  • Vue--数据传输
  • 初识MongoDB分片
  • 从重复到重用
  • 前端工程化(Gulp、Webpack)-webpack
  • 区块链技术特点之去中心化特性
  • 如何胜任知名企业的商业数据分析师?
  • 想晋级高级工程师只知道表面是不够的!Git内部原理介绍
  • Spark2.4.0源码分析之WorldCount 默认shuffling并行度为200(九) ...
  • # Java NIO(一)FileChannel
  • (1)SpringCloud 整合Python
  • (20050108)又读《平凡的世界》
  • (Arcgis)Python编程批量将HDF5文件转换为TIFF格式并应用地理转换和投影信息
  • (C语言)二分查找 超详细
  • (delphi11最新学习资料) Object Pascal 学习笔记---第5章第5节(delphi中的指针)
  • (delphi11最新学习资料) Object Pascal 学习笔记---第7章第3节(封装和窗体)
  • (delphi11最新学习资料) Object Pascal 学习笔记---第8章第2节(共同的基类)
  • (NO.00004)iOS实现打砖块游戏(九):游戏中小球与反弹棒的碰撞
  • (二)hibernate配置管理
  • (附源码)spring boot校园拼车微信小程序 毕业设计 091617
  • (附源码)springboot 基于HTML5的个人网页的网站设计与实现 毕业设计 031623
  • (附源码)计算机毕业设计SSM智慧停车系统
  • (论文阅读笔记)Network planning with deep reinforcement learning
  • (译) 函数式 JS #1:简介
  • (转贴)用VML开发工作流设计器 UCML.NET工作流管理系统
  • .gitignore文件—git忽略文件
  • .NET HttpWebRequest、WebClient、HttpClient
  • .Net Memory Profiler的使用举例
  • .NET 材料检测系统崩溃分析