ASP.NET MVC在服务端把异步上传的图片裁剪成不同尺寸分别保存,并设置上传目录的尺寸限制
Posted on 2015-08-04 11:07 米粒3 阅读(335) 评论(0) 编辑 收藏 举报我曾经试过使用JSAjaxFileUploader
插件来把文件、照片以异步的方式上传,就像"MVC文件图片ajax上传轻量级解决方案,使用客户端JSAjaxFileUploader插件01-单文件上传"中说的,这种方法足够轻、足够好。但今天,要在前面的基础上再增加2个需求:
1、异步判断上传的图片是否超过最大限制
2、把上传的图片裁剪成大中小3张图片,分别保存,删除的时候一块被删除
在项目根目录下的指定文件夹AjaxUpload
中同时有了大中小3张图片。
点击图片行的删除按钮或重新上传新的图片,原先的大中小3张图片一块被删除。重新上传新图片:
在项目根目录下的指定文件夹AjaxUpload
中同时有了新的大中小3张图片。
前端还是使用JSAjaxFileUploader
插件,后端使用ImageResizer
组件实现对图片的裁剪和保存。
当前端拿到异步请求的返回结果后,需要显示图片、记录下图片的名称、错误信息等,可以把这些信息封装到UploadFileResult
类中,让服务端以json格式返回。
http://www.cnblogs.com/namespace MvcApplication1.Models
{
http://www.cnblogs.com/public http://www.cnblogs.com/class UploadFileResult
{
http://www.cnblogs.com/public http://www.cnblogs.com/string LargeFileName { http://www.cnblogs.com/get; http://www.cnblogs.com/set; } http://www.cnblogs.com///带后缀名的图片名称,比如:20141112_large.jpg
http://www.cnblogs.com/public http://www.cnblogs.com/string MediumFileName { http://www.cnblogs.com/get; http://www.cnblogs.com/set; }
http://www.cnblogs.com/public http://www.cnblogs.com/string SmallFileName { http://www.cnblogs.com/get; http://www.cnblogs.com/set; }
http://www.cnblogs.com/public http://www.cnblogs.com/int Length { http://www.cnblogs.com/get; http://www.cnblogs.com/set; } http://www.cnblogs.com///图片的字节数
http://www.cnblogs.com/public http://www.cnblogs.com/string Type { http://www.cnblogs.com/get; http://www.cnblogs.com/set; } http://www.cnblogs.com///图片的类型:image/jpeg
http://www.cnblogs.com/public http://www.cnblogs.com/bool IsValid { http://www.cnblogs.com/get; http://www.cnblogs.com/set; } http://www.cnblogs.com///用来判断是否超过尺寸最大限制
http://www.cnblogs.com/public http://www.cnblogs.com/string Message { http://www.cnblogs.com/get; http://www.cnblogs.com/set; }
http://www.cnblogs.com/public http://www.cnblogs.com/string LargeFilePath { http://www.cnblogs.com/get; http://www.cnblogs.com/set; } http://www.cnblogs.com///图片的保存路径:~/AjaxUpload/20141112_large.jpg
http://www.cnblogs.com/public http://www.cnblogs.com/string MediumFilePath { http://www.cnblogs.com/get; http://www.cnblogs.com/set; }
http://www.cnblogs.com/public http://www.cnblogs.com/string SmallFilePath { http://www.cnblogs.com/get; http://www.cnblogs.com/set; }
}
}
以上,
○ LargeFileName
用来保存裁剪大图的名称,类似"20141112_large.jpg",当前台需要删除图片的时候,还需要把这个图片名称传递给服务端,再到指定文件夹删除图片。
○ LargeFilePath
用来保存图片的路径,类似"~/AjaxUpload/20141112_large.jpg",前台显示图片的时候需要这个。
○ IsValid
为true表示可以裁剪保存图片,为false表示超过最大的尺寸限制,取消上传
通过NuGet安装ImageResizer。安装完后,在"引用"下面多了一个ImageResizer组件。
创建HomeController
,主要完成以下工作:
1、接收前台上传图片,裁剪成大中小图片并分别保存
2、接收前台需要删除的图片名称,在指定文件夹中同时删除大中小图片
3、提供递归统计指定文件夹大小的方法
......
http://www.cnblogs.com/using System;
http://www.cnblogs.com/using System.Collections.Generic;
http://www.cnblogs.com/using System.IO;
http://www.cnblogs.com/using System.Web;
http://www.cnblogs.com/using System.Web.Mvc;
http://www.cnblogs.com/using ImageResizer;
http://www.cnblogs.com/using MvcApplication1.Models;
http://www.cnblogs.com/namespace MvcApplication1.Controllers
{
http://www.cnblogs.com/public http://www.cnblogs.com/class HomeController : Controller
{
http://www.cnblogs.com/public ActionResult Index()
{
http://www.cnblogs.com/return View();
}
[HttpPost]
http://www.cnblogs.com/public ActionResult UploadFile()
{
http://www.cnblogs.com///需要返回给前台的结果
List<UploadFileResult> results = http://www.cnblogs.com/new List<UploadFileResult>();
http://www.cnblogs.com///遍历从前台传递而来的文件
http://www.cnblogs.com/foreach (http://www.cnblogs.com/string file http://www.cnblogs.com/in Request.Files)
{
http://www.cnblogs.com///把每一个上传文件封装成HttpPostedFileBase
HttpPostedFileBase hpf = Request.Files[file] http://www.cnblogs.com/as HttpPostedFileBase;
http://www.cnblogs.com///如果前台传来的文件集合中有null,继续遍历其他文件
http://www.cnblogs.com/if (hpf.ContentLength == 0 || hpf == http://www.cnblogs.com/null)
{
http://www.cnblogs.com/continue;
}
http://www.cnblogs.com///给上传文件改名
http://www.cnblogs.com/string date = DateTime.Now.ToString("http://www.cnblogs.com/yyyyMMddhhmmss");
http://www.cnblogs.com///目标文件夹的相对路径 ImageSize需要的格式
http://www.cnblogs.com/string pathForSaving = Server.MapPath("http://www.cnblogs.com/~/AjaxUpload/");
http://www.cnblogs.com///目标文件夹的相对路径 统计文件夹大小需要的格式
http://www.cnblogs.com/string pathForSaving1 = Server.MapPath("http://www.cnblogs.com/~/AjaxUpload");
http://www.cnblogs.com///保存文件并返回结果
http://www.cnblogs.com/if (http://www.cnblogs.com/this.CreateFolderIfNeeded(pathForSaving))
{
http://www.cnblogs.com/long currentSize = GetDirectoryLength(pathForSaving1);
http://www.cnblogs.com///如果大于最大限制,直接返回json信息
http://www.cnblogs.com///1M=1024*1024个字节
http://www.cnblogs.com/if (currentSize + hpf.ContentLength > 50 * 1024 * 1024)http://www.cnblogs.com///最大允许50兆
{
results.Add(http://www.cnblogs.com/new UploadFileResult()
{
LargeFileName = "http://www.cnblogs.com/",
LargeFilePath = "http://www.cnblogs.com/",
MediumFileName = "http://www.cnblogs.com/",
MediumFilePath = "http://www.cnblogs.com/",
SmallFileName = "http://www.cnblogs.com/",
SmallFilePath = "http://www.cnblogs.com/",
IsValid = http://www.cnblogs.com/false,
Length = hpf.ContentLength,
Message = "http://www.cnblogs.com/超过最大限制无法上传",
Type = hpf.ContentType
});
}
http://www.cnblogs.com/else http://www.cnblogs.com///如果小于最大限制,才保存大中小图片
{
http://www.cnblogs.com///保存图片的各种版本:小图,中图,大图
var versions = http://www.cnblogs.com/new Dictionary<http://www.cnblogs.com/string, http://www.cnblogs.com/string>();
versions.Add("http://www.cnblogs.com/_small", "http://www.cnblogs.com/maxwidth=50&maxheight=50&format=jpg");
versions.Add("http://www.cnblogs.com/_medium", "http://www.cnblogs.com/maxwidth=200&maxheight=200&format=jpg");
versions.Add("http://www.cnblogs.com/_large", "http://www.cnblogs.com/maxwidth=600&maxheight=600&format=jpg");
http://www.cnblogs.com///保存各个版本的缩略图
http://www.cnblogs.com/foreach (var key http://www.cnblogs.com/in versions.Keys)
{
hpf.InputStream.Seek(0, SeekOrigin.Begin);
ImageBuilder.Current.Build(http://www.cnblogs.com/new ImageJob(
hpf.InputStream,
pathForSaving + date + key, http://www.cnblogs.com///不带后缀名的图片名称
http://www.cnblogs.com/new Instructions(versions[key]),
http://www.cnblogs.com/false,http://www.cnblogs.com///是否保留原图
http://www.cnblogs.com/true));http://www.cnblogs.com///是否增加后缀
}
results.Add(http://www.cnblogs.com/new UploadFileResult()
{
LargeFileName = date + "http://www.cnblogs.com/_large" + "http://www.cnblogs.com/.jpg",
LargeFilePath = Url.Content(String.Format("http://www.cnblogs.com/~/AjaxUpload/{0}", date + "http://www.cnblogs.com/_large" + "http://www.cnblogs.com/.jpg")),
MediumFileName = date + "http://www.cnblogs.com/_medium" + "http://www.cnblogs.com/.jpg",
MediumFilePath = Url.Content(String.Format("http://www.cnblogs.com/~/AjaxUpload/{0}", date + "http://www.cnblogs.com/_mediume" + "http://www.cnblogs.com/.jpg")),
SmallFileName = date + "http://www.cnblogs.com/_small" + "http://www.cnblogs.com/.jpg",
SmallFilePath = Url.Content(String.Format("http://www.cnblogs.com/~/AjaxUpload/{0}", date + "http://www.cnblogs.com/_small" + "http://www.cnblogs.com/.jpg")),
IsValid = http://www.cnblogs.com/true,
Length = hpf.ContentLength,
Message = "http://www.cnblogs.com/上传成功",
Type = hpf.ContentType
});
}
}
}
http://www.cnblogs.com///单文件上传,实际上results中只有一个元素
http://www.cnblogs.com/return Json(http://www.cnblogs.com/new
{
largename = results[0].LargeFileName,
largepath = results[0].LargeFilePath,
mediumname = results[0].MediumFileName,
mediumpath = results[0].MediumFilePath,
smallname = results[0].SmallFileName,
smallpath = results[0].SmallFilePath,
type = results[0].Type,
size = http://www.cnblogs.com/string.Format("http://www.cnblogs.com/{0} bytes", results[0].Length),
msg = results[0].Message,
isvalid = results[0].IsValid
});
}
http://www.cnblogs.com///根据文件名称删除文件
[HttpPost]
http://www.cnblogs.com/public ActionResult DeleteFileByNames(http://www.cnblogs.com/string largename, http://www.cnblogs.com/string mediumname, http://www.cnblogs.com/string smallname)
{
http://www.cnblogs.com/string pathForSaving = Server.MapPath("http://www.cnblogs.com/~/AjaxUpload");
System.IO.File.Delete(Path.Combine(pathForSaving, largename));
System.IO.File.Delete(Path.Combine(pathForSaving, mediumname));
System.IO.File.Delete(Path.Combine(pathForSaving, smallname));
http://www.cnblogs.com/return Json(http://www.cnblogs.com/new
{
msg = http://www.cnblogs.com/true
});
}
http://www.cnblogs.com//// <summary>
http://www.cnblogs.com//// 根据目标文件夹的相对路径创建文件夹
http://www.cnblogs.com//// 如果目标文件夹不存在,就创建;存在就不创建
http://www.cnblogs.com//// 只有在创建目标文件夹发生异常的时候才返回false
http://www.cnblogs.com//// </summary>
http://www.cnblogs.com//// <param name="path">目标文件夹的相对路径</param>
http://www.cnblogs.com//// <returns></returns>
http://www.cnblogs.com/private http://www.cnblogs.com/bool CreateFolderIfNeeded(http://www.cnblogs.com/string path)
{
http://www.cnblogs.com/bool result = http://www.cnblogs.com/true;
http://www.cnblogs.com/if (!Directory.Exists(path))
{
http://www.cnblogs.com/try
{
Directory.CreateDirectory(path);
}
http://www.cnblogs.com/catch (Exception)
{
result = http://www.cnblogs.com/false;
}
}
http://www.cnblogs.com/return result;
}
http://www.cnblogs.com//// <summary>
http://www.cnblogs.com//// 根据目标文件夹的相对路径递归计算该文件夹的大小
http://www.cnblogs.com//// </summary>
http://www.cnblogs.com//// <param name="path">用相对路径表示的目标文件夹</param>
http://www.cnblogs.com//// <returns></returns>
http://www.cnblogs.com/private http://www.cnblogs.com/static http://www.cnblogs.com/long GetDirectoryLength(http://www.cnblogs.com/string path)
{
http://www.cnblogs.com///如果目标文件夹不存在就返回0
http://www.cnblogs.com/if (!Directory.Exists(path))
{
http://www.cnblogs.com/return 0;
}
http://www.cnblogs.com/long size = 0;
http://www.cnblogs.com///获取目标文件夹的信息
DirectoryInfo di = http://www.cnblogs.com/new DirectoryInfo(path);
http://www.cnblogs.com///遍历目标文件夹下的所有文件遍历累计每个文件的大小
http://www.cnblogs.com/foreach (FileInfo fi http://www.cnblogs.com/in di.GetFiles())
{
size += fi.Length;
}
http://www.cnblogs.com///获取目标文件夹下的所有子文件夹
DirectoryInfo[] dis = di.GetDirectories();
http://www.cnblogs.com///如果确实有子文件夹
http://www.cnblogs.com/if (dis.Length > 0)
{
http://www.cnblogs.com///遍历这些子文件夹
http://www.cnblogs.com/for (http://www.cnblogs.com/int i = 0; i < dis.Length; i++)
{
http://www.cnblogs.com///递归统计累计大小
size += GetDirectoryLength(dis[i].FullName);
}
}
http://www.cnblogs.com/return size;
}
}
}
以上,
○ UploadFile
方法中,通过Request.Files
拿到所有的上传图片,然后遍历这些图片,通过Request.Files[key]
获取某个图片,把该图片转换成HttpPostedFileBase
类型。在裁剪保存图片之前,使用GetDirectoryLength
方法获取当前文件夹的尺寸,如果没有超过尺寸的最大限制,就使用ImageResizer
把图片裁剪成大中小3张图片,并分别保存。
○ DeleteFileByNames
方法中,从前台接收大中小图片的名称,再到根目录下的指定文件夹AjaxUpload
中删除大中小3张图片。
在_Layout.cshtml
中引入相关css、js文件。JQuery.JSAjaxFileUploaderSingle.js
文件已经做了汉化,详细参考这里。
<head>
<meta charset="http://www.cnblogs.com/utf-8" />
<meta name="http://www.cnblogs.com/viewport" content="http://www.cnblogs.com/width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("http://www.cnblogs.com/~/Content/css")
<link href="http://www.cnblogs.com/~/Content/JSAjaxFileUploader/JQuery.JSAjaxFileUploader.css" rel="http://www.cnblogs.com/stylesheet" />
@Scripts.Render("http://www.cnblogs.com/~/bundles/modernizr")
@Scripts.Render("http://www.cnblogs.com/~/bundles/jquery")
<script src="http://www.cnblogs.com/~/JSAjaxFileUploader/JQuery.JSAjaxFileUploaderSingle.js"></script>
</head>
<body>
@RenderBody()
@RenderSection("http://www.cnblogs.com/scripts", required: http://www.cnblogs.com/false)
</body>
创建Home/Index.cshtml
视图,主要工作包括:
1、处理图片上传,每次上传前需要把原先的3张图片删除,如果上传成功显示小图的缩略图,如果上传失败,给出错误提示。
2、提供一个动态创建图片行表格的方法
3、提供一个删除大中小图片的方法,向服务端发送3张图片的名称
......
@{
ViewBag.Title = "http://www.cnblogs.com/Index";
Layout = "http://www.cnblogs.com/~/Views/Shared/_Layout.cshtml";
}
<style type="http://www.cnblogs.com/text/css">
#tb table {
border-collapse: collapse;
width: 600px;
}
#tb td {
text-align: center;
padding-top: 5px;
width: 25%;
}
#tb tr {
background-color: #E3E3E3;
line-height: 35px;
}
.limit {
color: red;
}
</style>
<div id="http://www.cnblogs.com/testId"></div>
<div id="http://www.cnblogs.com/tb">
<table id="http://www.cnblogs.com/tbl">
<tbody>
</tbody>
</table>
</div>
<div>
<span http://www.cnblogs.com/class="http://www.cnblogs.com/limit"></span>
</div>
@section scripts
{
<script type="http://www.cnblogs.com/text/javascript">
$(function() {
http://www.cnblogs.com///隐藏显示图片的表格
$('#tbl').hide();
http://www.cnblogs.com///图片上传
$('#testId').JSAjaxFileUploader({
uploadUrl: '@Url.Action("http://www.cnblogs.com/UploadFile","http://www.cnblogs.com/Home")',
inputText: '选择上传文件',
http://www.cnblogs.com///fileName: 'photo',
maxFileSize: 512000, http://www.cnblogs.com///Max 500 KB file 1kb=1024字节
allowExt: 'gif|jpg|jpeg|png',
zoomPreview: http://www.cnblogs.com/false,
zoomWidth: 360,
zoomHeight: 360,
beforesend: function (file) {http://www.cnblogs.com///每次点击都要删除原先的
http://www.cnblogs.com/if ($('.largeImgName').text() != "http://www.cnblogs.com/" && $('.mediumImgName').text() != "http://www.cnblogs.com/" && $('.smallImgName').text() != "http://www.cnblogs.com/") {
deleteImg();
$('#tbl').hide();
}
},
success: function (data) {
http://www.cnblogs.com/if (!data.isvalid) { http://www.cnblogs.com///如果尺寸超过最大限制
$('.limit').css("http://www.cnblogs.com/display", "http://www.cnblogs.com/block");
$('.limit').text(data.msg);
http://www.cnblogs.com/return;
} http://www.cnblogs.com/else {
$('.limit').css("http://www.cnblogs.com/display", "http://www.cnblogs.com/none");
createTableTr();
$('#tbl').show();
$('.showImg').attr("http://www.cnblogs.com/src", data.smallpath);http://www.cnblogs.com///显示小图片
$('.largeImgName').text(data.largename); http://www.cnblogs.com///显示大图的名称
$('.mediumImgName').text(data.mediumname); http://www.cnblogs.com///显示中图的名称
$('.smallImgName').text(data.smallname); http://www.cnblogs.com///显示小图的名称
}
},
error: function (data) {
alert(data.msg);
}
});
http://www.cnblogs.com///点击删除链接删除刚上传图片
$('#tbl').on("http://www.cnblogs.com/click", "http://www.cnblogs.com/.delImg", function () {
deleteImg();
http://www.cnblogs.com///window.location.reload();
});
});
http://www.cnblogs.com///创建表格
function createTableTr() {
var table = $('#tbl');
table.append("http://www.cnblogs.com/<tr><td><img class='showImg'/></td><td colspan='2'><span class='largeImgName'></span><br/><span class='mediumImgName'></span><br/><span class='smallImgName'></span></td><td><a class='delImg' href='javascript:void(0)'>删除</a></td></tr>");
}
http://www.cnblogs.com///删除图片方法:点击删除链接或上传新图片删除原先图片用到
function deleteImg() {
$.ajax({
cache: http://www.cnblogs.com/false,
url: '@Url.Action("http://www.cnblogs.com/DeleteFileByNames", "http://www.cnblogs.com/Home")',
type: "http://www.cnblogs.com/POST",
data: { largename: $('.largeImgName').text(), mediumname: $('.mediumImgName').text(), smallname: $('.smallImgName').text() },
success: function (data) {
http://www.cnblogs.com/if (data.msg) {
http://www.cnblogs.com///alert("图片删除成功");
$('.delImg').parent().parent().remove();
}
},
error: function (jqXhr, textStatus, errorThrown) {
alert("http://www.cnblogs.com/出错了 '" + jqXhr.status + "http://www.cnblogs.com/' (状态: '" + textStatus + "http://www.cnblogs.com/', 错误为: '" + errorThrown + "http://www.cnblogs.com/')");
}
});
}
</script>
}