本篇通过在配置文件中设置,对上传图片修剪后保存到指定文件夹。

相关兄弟篇:

MVC文件上传01-使用jquery异步上传并客户端验证类型和大小 
MVC文件上传02-使用HttpPostedFileBase上传多个文件  
MVC文件上传03-使用Request.Files上传多个文件
MVC文件上传04-使用客户端jQuery-File-Upload插件和服务端Backload组件实现多文件异步上传  
MVC文件上传05-使用客户端jQuery-File-Upload插件和服务端Backload组件自定义上传文件夹 
MVC文件上传06-使用客户端jQuery-File-Upload插件和服务端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格式不允许:

参考资料:
※ 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案例

转载于:https://www.cnblogs.com/darrenji/p/3620618.html

MVC文件上传07-使用客户端jQuery-File-Upload插件和服务端Backload组件裁剪上传图片...相关推荐

  1. spring mvc文件上传小例子

    spring mvc文件上传小例子 1.jsp页面 <%@page contentType="text/html;charset=UTF-8"%> <%@page ...

  2. 文件上传案例的客户端

    package com.learn.demo02.FileUpload;import java.io.FileInputStream; import java.io.IOException; impo ...

  3. Spring MVC文件上传示例教程 - 单个和多个文件

    Spring MVC文件上传示例教程 - 单个和多个文件 文件上传是任何Web应用程序中非常常见的任务.我们之前已经看过如何在Servlet和Struts2文件上传中上传文件.今天我们将学习Sprin ...

  4. html5支持ajax和jQuery吗,使用HTML5文件上传与AJAX和jQuery(Using HTML5 file uploads with AJAX and jQuery)...

    使用HTML5文件上传与AJAX和jQuery(Using HTML5 file uploads with AJAX and jQuery) 诚然,Stack Overflow上有类似的问题,但似乎并 ...

  5. js文件上传以及js清空input file值

    最近项目中遇到文件上传的案例, 之前涉及文件上传的较少, 今天针对js文件上传的案例做一个详细的教程,方便日后查阅! 本教程从 原生JS, jQuery, 两处着手简单介绍文件上传案例 1.原生JS ...

  6. SpringBoot文件上传异常之提示The temporary upload location xxx is not valid

    SpringBoot文件上传异常之提示The temporary upload location xxx is not valid 参考文章: (1)SpringBoot文件上传异常之提示The te ...

  7. 【Spring】Spring MVC文件上传--整合bootstrap-fileinput和jQuery-File-Upload

    前言 这里分享两个使用Spring MVC进行文件上传的简单示例, 分别整合bootstrap-fileinput 和 Jquery File Upload , 代码十分简单, 都是入门的示例,因此这 ...

  8. ASP.NET MVC 文件上传和文件下载 以及 文件下载的几种方法

    1.序言 最近项目中需要用到这个功能点,但是网上下载的时候总是出现乱码.所以趁着这个时间自己整理出了一份,以后需要的时候就直接看自己的博客就行了.已经测试过:在谷歌.火狐.IE等浏览器上都不会出现乱码 ...

  9. Spring MVC文件上传

    1.配置xml文件 1 <!-- 指定文件上传解析 名字不能乱给 --> 2 <bean name="multipartResolver" class=" ...

最新文章

  1. C++实现hopcroft karp霍普克洛夫特-卡普算法(附完整源码)
  2. 如何使用悲观锁定修复乐观锁定竞争条件
  3. Java线程面试题,值得一看!
  4. docker jfrog-oss
  5. 解决outlook2013设置错误无法启动
  6. Eclipse+Maven创建webapp项目二 (转)
  7. 直方图中最大的矩形(单调栈2)
  8. 清华学霸组团的工业 AIoT 创企再获数千万融资:玩家应推动在边缘 AI 芯片上跑算法...
  9. java int stack_java中int算法的有趣现象
  10. 票房连创新高 数据安全不能成为《熊出没》“拖油瓶”
  11. 2014大学计算机操作系统,郑州大学软件学院2013-2014《计算机操作系统》试题及答案...
  12. 红外遥控器解码串口输出模块结合51单片机+oled屏幕实现遥控器红外解锁( STC89C52RC)
  13. Arduino 交通灯实验
  14. Little_Women6.txt
  15. 喜迎进博会 欢聚环球港 共享消费城——2021环球商业年会暨城市综合体论坛圆满举行
  16. android通知栏的点击事件,android自定义通知栏以及点击事件
  17. 软考高级 真题 2014年下半年 信息系统项目管理师 综合知识
  18. 键盘上特殊符号的中英文名称
  19. f8恢复计算机忘记用户密码,win10系统电脑开机密码忘了的恢复方法
  20. 科一科四题库技巧软件源码

热门文章

  1. NYOJ458 - 小光棍数
  2. JSP→JavaWeb简介、Tomcat服务器安装启动测试目录、Tomcat手动创建项目、开发工具MyEclipse与Eclipse配置环境、MyEclipse创建Web程序目录、修改Tomcat端口
  3. Python入门--以主程序的方式运行,if __name__==‘__main__‘
  4. eplices如何导入外部代码_搜索引擎的蜘蛛是如何爬的
  5. 2014蓝桥杯:地宫取宝(DFS详解)
  6. Codecraft-18 and Codeforces Round #458: D. Bash and a Tough Math Puzzle(线段树)
  7. bzoj 3406: [Usaco2009 Oct]Invasion of the Milkweed 乳草的入侵
  8. OPNET网络仿真分析-1.1.3、OPNET Modeler
  9. Python实现简单的人脸打卡系统
  10. 荣耀10 原版android,荣耀V10新内置壁纸