使用jQuery.FileUpload插件和Backload组件裁剪上传图片

□ 思路

1、自定义控制器继承Backload的默认控制器BackloadController
2、自定义一个jQuery File Upload初始化js文件,使用自定义控制器的方法
3、在视图页面调用自定义jQuery File Upload初始化js文件

□ 安装Backload组件和jQuery File Upload插件

→在"程序包管理器控制台"输入:Install-Package Backload

→在"程序包管理器控制台"输入: Install-Package JQuery_File_Upload_Plugin

□ 自定义BaseController继承BackloadController

   1:  using System.Web.Mvc;
   2:   
   3:  namespace MvcApplication7.Controllers
   4:  {
   5:      public class BaseController : BackloadController
   6:      {
   7:          //public ActionResult Index()
   8:          //{
   9:          //    return View();
  10:          //}
  11:   
  12:          public async Task<ActionResult> FileHandler()
  13:          {
  14:              ActionResult result = await base.HandleRequestAsync();
  15:              return result;
  16:          }
  17:      }
  18:  }

□ 自定义HomeController继承BaseController

   1:  using System.Web.Mvc;
   2:  namespace MvcApplication7.Controllers
   3:  {
   4:      public class HomeController : BaseController
   5:      {
   6:          public ActionResult Index()
   7:          {
   8:              return View();
   9:          }
  10:      }
  11:  }

□ 自定义用于初始化jQuery File Upload的js文件main.js

其中,还限制了上传文件的格式。

   1:  $(function () {
   2:      ‘use strict‘;
   3:   
   4:      var url = ‘/Base/FileHandler‘;
   5:      // Initialize the jQuery File Upload widget:
   6:      $(‘#fileupload‘).fileupload({
   7:          // Uncomment the following to send cross-domain cookies:
   8:          //xhrFields: {withCredentials: true},
   9:          url: url,
  10:          acceptFileTypes: /(jpg)|(jpeg)|(png)|(gif)$/i // Allowed file types
  11:      });
  12:   
  13:      // Enable iframe cross-domain access via redirect option:
  14:      $(‘#fileupload‘).fileupload(
  15:          ‘option‘,
  16:          ‘redirect‘,
  17:          window.location.href.replace(
  18:              /\/[^\/]*$/,
  19:              ‘/cors/result.html?%s‘
  20:          )
  21:      );
  22:   
  23:      // Load existing files by an initial ajax request to the server after page loads up
  24:      // This is done by a simple jQuery ajax call, not by the FIle Upload plugin.,
  25:      // but the results are passed to the plugin with the help of the context parameter: 
  26:      // context: $(‘#fileupload‘)[0] and the $(this)... call in the done handler. 
  27:      // With ajax.context you can pass a JQuery object to the event handler and use "this".
  28:      $(‘#fileupload‘).addClass(‘fileupload-processing‘);
  29:      $.ajax({
  30:          // Uncomment the following to send cross-domain cookies:
  31:          //xhrFields: {withCredentials: true},
  32:          url: url,
  33:          dataType: ‘json‘,
  34:          context: $(‘#fileupload‘)[0]
  35:      }).always(function () {
  36:          $(this).removeClass(‘fileupload-processing‘);
  37:      }).done(function (result) {
  38:          $(this).fileupload(‘option‘, ‘done‘)
  39:              .call(this, null, { result: result });
  40:      });
  41:  });
  42:   
  43:  $("document").ready(function () {
  44:      $(‘#fileupload‘)
  45:          .bind(‘fileuploaddestroy‘, function (e, data) {
  46:              // Event handler example. Do something if you need after file has been deleted on the server. 
  47:              // (Refer to the client side documentatio).
  48:          });
  49:   
  50:  });
  51:   

□ _Layout.cshtml布局视图

   1:  <!DOCTYPE html>
   2:  <html>
   3:  <head>
   4:      <meta charset="utf-8" />
   5:      <meta name="viewport" content="width=device-width" />
   6:      <title>@ViewBag.Title</title>
   7:      @Styles.Render("~/Content/css")
   8:      @Styles.Render("~/Content/themes/base/css")
   9:      @Styles.Render("~/bundles/fileupload/bootstrap/BasicPlusUI/css")
  10:      @Scripts.Render("~/bundles/modernizr")
  11:  </head>
  12:  <body>
  13:      @RenderBody()
  14:   
  15:      @Scripts.Render("~/bundles/jquery")
  16:      @Scripts.Render("~/bundles/jqueryui")
  17:      @Scripts.Render("~/bundles/fileupload/bootstrap/BasicPlusUI/js")
  18:      @RenderSection("scripts", required: false)
  19:  </body>
  20:  </html>
  21:   

□ Home/Index.cshtml视图

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

<style type="text/css">
    .table-striped {
        width: 65%;
    }
</style>

<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

   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" /></configSections>
   5:    <configSections>
   6:    <backload configSource="Web.backload.config" />
   7:  </configuration>

□ 所有Backload的配置放在Web.backload.config中

   1:  <?xml version="1.0"?>
   2:   
   3:  <backload xsi:noNamespaceSchemaLocation="Web.Backload.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:name="urn:backload-schema" thumbsUrlPattern="{Backload}">
   4:   
   5:    <images width="200" height="200" dpi="96" resizeMode="ratio" />
   6:    <thumbnails path="" width="60" height="60" canvasColor="#00000000" resizeMode="place" imageType="image/png" />
   7:    <fileSystem filesRoot="~/Upload" />
   8:    <cacheManager lastModified="true" etag="true"/>
   9:  </backload>

● width和height实际上设置的是画布Canvas的大小。
● 没有resizeMode属性:保持上传图片的大小不变
● resizeMode="ration": 当图片的宽度大于画布的宽度,图片的宽度修剪为画布的宽度,图片的高度等比例缩放,画布背景不显示
● resizeMode="fit": 当图片的宽度大于画布的宽度,图片的宽度修剪为画布的宽度,图片的高度等比例缩放,画布背景显示
● resizeMode="place": 当图片的宽度小于画布的宽度,图片的宽度修剪为画布的宽度,图片的高度等比例缩放,画布背景显示
● resizeMode="crop": 图片的宽度或高度充满画布的宽度或高度,空白的画布区域裁剪掉。

□ 结果

上传界面:

由于设置了path="",所以没有了缩略图:

由于设置了resizeMode="ratio",上传图片宽度不变,高度按比例缩小:

□ 设置文件夹带缩略图文件夹path="_thumb"

   1:  <backload xsi:noNamespaceSchemaLocation="Web.Backload.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:name="urn:backload-schema" thumbsUrlPattern="{Backload}">
   2:   
   3:    <images width="200" height="200" dpi="96" resizeMode="ratio" />
   4:    <thumbnails path="_thumb" width="60" height="60" canvasColor="#00000000" resizeMode="place" imageType="image/png" />
   5:    <fileSystem filesRoot="~/Upload" />
   6:    <cacheManager lastModified="true" etag="true"/>
   7:  </backload>

增加一个图片:

由于设置了path="_thumb",所以有了缩略图文件夹:

由于缩略图设置了resizeMode="place",图片宽度等于画布宽度,高度等比例缩放,显示背景:

由于在main.js中设置了acceptFileTypes: /(jpg)|(jpeg)|(png)|(gif)$/i,pdf格式不允许:

时间: 2024-11-05 18:31:07

使用jQuery.FileUpload插件和Backload组件裁剪上传图片的相关文章

使用jQuery.FileUpload插件和服Backload组件自定义上传文件夹

在零配置情况下,文件的上传文件夹是根目录下的Files文件夹,如何自定义文件的上传文件夹呢? □ 在web.config中配置 1: <configuration> 2: <configSections> 3: ... 4: <section name="backload" type="Backload.Configuration.BackloadSection, Backload, Version=1.9.3.1, Culture=neutra

新鲜出炉的jquery fileupload 插件

内容属原创,转载请注明出处 为什么做这个东东 项目中需要用到一个多附件上传的控件,找了一圈没找到中意的(唯一一个中意点的还不开源,费用比较高),这不,只得自己抡刀上了. 需求是什么 这么个上传的东东,要做哪些事情呢? 必须要干的事情: 1. 不能太丑,可以很素. 原生的input file实在和项目主体不太搭配,需要另外想办法. 2. 需要支持上传多个附件,比如后台有个字段叫做 影像资料,这个影像资料,也许就是一张正面照,也许,还有一堆的证件照,需要支持多个. 3. 需要一个页面上支持多个这样的

使用 jQuery FileUpload 插件实现异步上传

首先,先做两个提前准备工作  1.下载插件 2.向项目导入需要的css样式和js样式 下面,开始实现 使用 jQuery FileUpload 插件实现异步上传 <!- jsp 页面  以添加一个学生为例子 -!> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html P

jquery.fileupload插件 ie9下不支持上传

根据https://github.com/blueimp/jQuery-File-Upload/wiki/Browser-support The following browsers support at least one form of AJAX style file uploads, either via XHR or via the Iframe Transport: Desktop browsers Google Chrome Apple Safari 4.0+ Mozilla Fir

基于jQuery功能非常强大的图片裁剪插件

今天我们要来介绍一款基于jQuery功能非常强大的图片裁剪插件,这款jQuery图片裁剪插件可以选择裁剪框的尺寸比例,可以设置高宽尺寸,同时可以设置图片翻转角度,当然也支持图片的缩放,裁剪框也可以用鼠标拖动.效果图如下: 在线预览   源码下载 来看看实现的代码,这里我们主要来看JavaScript代码 获取图片的Canvas画布: function getSourceCanvas(image, data) { var canvas = $('<canvas>')[0], context =

asp.net 实现在线打印功能,jQuery打印插件PrintArea实现自动分页

使用的组件:jQuery打印插件PrintArea,有兴趣的可以研究一下. 使用方法略过,这里将介绍如何实现打印多页是可以分页. 现在提供两种方法思路: 1.根据特定的打印机型号和使用的纸张类型,然后用JS来算出每页多高,按照每张纸的高度来进行适当的增减高度.(这种方式缺点就是只能针对单中类型的纸张,计算十分的繁琐,要些很多加减法 -_-);). 参考A4纸高度的网页:http://www.jb51.net/office/word/67360.html 2.在如上一个思路的方式,试着查找能不能自

jQuery Easy UI Draggable(拖动)组件

上文已经提到过了 jQuery EasyUI插件引用一般我们常用的有两种方式(排除easyload加载方式),所以本篇要总结的Draggable组件同样有两种方式加载: (1).使用class加载方式: <div id="box" class="easyui-draggable" style="width:400px;height:200px;background:red;"> 内容部分 </div> (2).JS 加载调

jQuery.uploadify文件上传组件实例讲解

1.jquery.uploadify简介 在ASP.NET中上传的控件有很多,比如.NET自带的FileUpload,以及SWFUpload,Uploadify等等,尤其后面两个控件的用户体验比较好,无刷新,带上传进度等等.在最近的短信平台开发中,使用Uploadify进行文件上传. Uploadify官网地址是:http://www.uploadify.com/ 可满足项目开发需求. 下载地址:http://www.uploadify.com/wp-content/uploads/files/

为JQuery写插件

很多场合,我们都会调用jQuery的插件去完成某个功能,比如slider. 如下图,做一个div,通过“$( "#slider" ).slider();”的方式直接将div变成slider,比起slider($('#slider'))更贴近jQuery的链式调用写法,可读性和通用性更好些. 那么,我们也来为jQuery写插件.便于项目中的组件化. 方法是非常简单的,那就写一个测试的demo来作为基础的验证吧. 定义html,假设我们要把test div修改成宽高都是200px,背景色为