MVC文件上传06-使用客户端jQuery-File-Upload插件和服务端Backload组件自定义控制器上传多个文件

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


MVC文件上传相关兄弟篇:

MVC文件上传01-使用jquery异步上传并客户端验证类型和大小 
MVC文件上传02-使用HttpPostedFileBase上传多个文件  
MVC文件上传03-使用Request.Files上传多个文件
MVC文件上传04-使用客户端jQuery-File-Upload插件和服务端Backload组件实现多文件异步上传  
MVC文件上传05-使用客户端jQuery-File-Upload插件和服务端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视图

展开

 

□ 在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

 

参考资料:
http://backload.org/ Backload官网
https://github.com/blackcity/Backload#examples Backload例子
http://nuget.org/packages/Backload/ nuget上的Backload

http://blueimp.github.io/jQuery-File-Upload/ jQuery File Upload官网
https://github.com/blueimp/jQuery-File-Upload/wiki  github上的jQuery File Upload介绍
https://github.com/blueimp/jQuery-File-Upload  github上的jQuery File Upload源码

https://www.nuget.org/packages/JQueryFileUpload_Demo_with_Backload/  下载jQuery File Upload结合Backload的MVC案例

posted @ 2014-03-24 00:09  Darren Ji  阅读(1146)  评论(0编辑  收藏  举报

我的公众号:新语新世界,欢迎关注。