MVC文件上传-使用jQuery.FileUpload和Backload组件实现文件上传

本篇使用客户端jQuery-File-Upload插件和服务端Badkload组件实现多文件异步上传。MVC文件上传相关兄弟篇: 

  处理文件上传的服务端组件Backload

用于处理文件上传的服务端组件。Backload与客户端文件上传插件(比如jQuery-File-Upload)配合使用,初步形成一个处理文件异步上传的解决方案。

□ Badkload的一些功能和特点

● 零配置:Backload提供默认BackloadDemoController用来处理上传文件请求。如果其它控制器也想拥有"Backload处理上传文件的超强能力",只需要继承BackloadDemoController就可以。
● 在web.config中显式配置
● 支持多种存储位置:文件夹、数据库(通过Entity Framework)、云存储(将来支持)
● 根据不同的请求上下文把上传文件保存到不同的位置
● 根据上传文件的不同类型保存到不同的位置
● 支持对图片的裁剪,而参数可以在web.confgig中配置
● 支持对多个图片的处理
● 支持图片类型转换
● 支持生成缩略图
● 支持在服务端创建唯一的文件名(GUIDs)
● 还可以在原始文件和修改文件之间建立映射,并返回给客户端一个友好的名称。
● 良好的可扩展性:通过实现Badkload的接口和使用ExportAttribute特性。
● 安全性:为控制器加上验证和授权
● 可调试:方便断点调试发现错误
...

□ 安装客户端jQuery-File-Upload插件和服务端Badkload组件,有2种方式:

1、分别安装客户端和服务端所需的插件和组件

● 安装服务端的Backload:

PM> Install-Package Backload

● 如果客户端选择使用jQuery-File-Upload插件,通过如下来安装这个客户端文件上传插件:

PM> Install-Package JQuery_File_Upload_Plugin

2、安装Query-File-Upload结合Backload实现文件上传的Demo,一次性安装客户端和服务端所需的插件和组件:

PM> Install-Package JQueryFileUpload_Demo_with_Backload

  例子:零配置实现多文件上传

□ 新建一个MVC4项目,工具--库程序包管理器--程序包管理器控制台,输入:

PM> Install-Package JQueryFileUpload_Demo_with_Backload

引用文件夹多了如下文件:
1

App_Start文件夹里多了如下BackloadConfig.cs文件,里面有jQuery File Upload插件所有需要的js和css文件:
9

Content文件夹多了如下文件:
2

Controller文件夹多了一个控制器:
4

Scripts文件夹多了如下文件:
5

Views文件夹多了如下文件夹和文件:
6

□ 运行http://localhost:1631/BackloadDemo/Index,发现如下问题:

1、工具--库程序包管理器--程序包管理器控制台,被禁用

关闭VS,重新打开就恢复。

2、报错

未能加载文件或程序集“WebGrease, Version=1.5.1.25624, Culture=neutral, PublicKeyToken=31bf3856ad364e35”或它的某一个依赖项。找到的程序集清单定义与程序集引用不匹配。 (异常来自 HRESULT:0x80131040)

通过"uninstall-package -f WebGrease"先卸载,然后通过"install-package WebGrease"再下载最新版本,问题解决。

□ 再次运行http://localhost:1631/BackloadDemo/Index

1

□ 添加2个上传文件,出现上传文件列表并配有缩略图

2

□ 分别点击"Start"按钮,上传成功后,"Start"按钮消失,出现"Delete"按钮。

3

□ 根目录下多了Files文件夹

4

□ File文件夹下不仅有上传的图片,还有一个存放缩略图的文件夹_thumbs:

5

□ 勾选上传文件列表中的一行,点击"Delete":

界面少了一行记录:
6

File文件夹下原先的图片也被删除:
7

  总结

● 仅仅通过PM> Install-Package JQueryFileUpload_Demo_with_Backload 安装了客户端文件上传插件jQuery-File-Upload和服务端文件处理组件Backload,没有做任何配置,就可以进行多个文件的上传。
● 文件默认被上传到根目录下的Files文件夹,需要这个文件夹的"写"权限。

□ BackloadDemoController是默认的控制器

   1:  using System.Web.Mvc;
   2:   
   3:  namespace MvcApplication6.Controllers
   4:  {
   5:      public class BackloadDemoController : Controller
   6:      {
   7:          //
   8:          // GET: /BackupDemo/
   9:          public ActionResult Index()
  10:          {
  11:              return View();
  12:          }
  13:      }
  14:  }

□ BackloadDemoController是默认的上传文件视图

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>JQuery File Upload Plugin with Backload demo installation</title>
    @Styles.Render("~/Content/themes/base/css")
    @Styles.Render("~/Content/css")

    <!-- We use Backloads. bundeling feature to register only those client side javascript and style files of the jQuery File Upload Plugin that are needed  -->
    @Styles.Render("~/bundles/fileupload/bootstrap/BasicPlusUI/css")

     <!-- Bootstrap CSS fixes for IE6 -->
    <!--[if lt IE 7]><link rel="stylesheet" href="/Content/FileUpload/css/bootstrap/bootstrap-ie6.debug.css"><![endif]-->
    
    <!--[if lt IE 9]><script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
    <!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><![endif]-->
</head>
<body>
    <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>Add files...</span>
                        <input type="file" name="files[]" multiple>
                    </span>
                    <button type="submit" class="btn btn-primary start">
                        <i class="icon-upload icon-white"></i>
                        <span>Start upload</span>
                    </button>
                    <button type="reset" class="btn btn-warning cancel">
                        <i class="icon-ban-circle icon-white"></i>
                        <span>Cancel upload</span>
                    </button>
                    <button type="button" class="btn btn-danger delete">
                        <i class="icon-trash icon-white"></i>
                        <span>Delete</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="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="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>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")

    <!-- We use Backloads. bundeling feature to register only those client side javascript and style files of the jQuery File Upload Plugin that are needed  -->
    @Scripts.Render("~/bundles/fileupload/bootstrap/BasicPlusUI/js")

    <!-- Initialize the jQuery File Upload Plugin -->
    <script src="~/Scripts/FileUpload/backload.demo.js"></script>
</body>
</html>

以上,html部分:
● <form id="fileupload" action="/Backload/UploadHandler" method="POST" enctype="multipart/form-data">放置添加、取消、上传等按钮
● <script id="template-upload" type="text/x-tmpl">上传文件列表
● 下载文件列表

css部分:
● @Styles.Render("~/Content/themes/base/css")
● @Styles.Render("~/Content/css")
● @Styles.Render("~/bundles/fileupload/bootstrap/BasicPlusUI/css") 使用Backloads的bundeling功能注册jQuery File Upload所需的css

js部分:
● @Scripts.Render("~/bundles/jquery")
● @Scripts.Render("~/bundles/jqueryui")
● @Scripts.Render("~/bundles/fileupload/bootstrap/BasicPlusUI/js") 使用Backloads的bundeling功能注册jQuery File Upload所需的js
● script src="~/Scripts/FileUpload/backload.demo.js"></script> 初始化jQuery File Upload

原文地址:https://www.cnblogs.com/wangsai/p/4113315.html