首页 > 代码库 > ASP.NET MVC中使用uploadify上传图片并按照规定大小压缩图片
ASP.NET MVC中使用uploadify上传图片并按照规定大小压缩图片
$(document).ready(function () { $(‘#uploadify‘).uploadify({ onUploadSuccess: function (file, returndata, response) { var data = http://www.mamicode.com/eval(‘(‘ + returndata + ‘)‘); if (response == true && data.Success == ‘true‘) { $("input[name=BACKIMG]").attr("value", data.FileName);//data.FileName为图片保存路径 $(‘#mainForm‘).submit(); } else { alert(data.Message); } }, ‘height‘: 20, ‘width‘: 35, ‘uploadLimit‘: 1, ‘queueSizeLimit‘: 1, ‘queueID‘: ‘fileQueue‘, ‘removeCompleted‘: false, ‘auto‘: false, ‘multi‘: false, ‘buttonText‘: ‘浏览图片‘, ‘swf‘: ‘@Url.Content("~/Scripts/uploadify/uploadify.swf")‘, ‘uploader‘: ‘@Url.Content("~/Scripts/uploadify/UploadAttach.ashx")‘ });
将图片上传到服务器的方法为UploadAttach.ashx
/// <summary> /// UploadAttach 的摘要说明 /// </summary> public class UploadAttach : IHttpHandler { public void ProcessRequest(HttpContext context) { HttpPostedFile fileData = context.Request.Files["fileData"]; string floder = context.Request["floder"]; if (fileData != null) { try { // 文件上传后的保存路径 string path = "~/img/"; string filePath = context.Server.MapPath(path); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } string saveFileName = Guid.NewGuid().ToString() + fileData.FileName; string newFilePath = filePath + saveFileName; fileData.SaveAs(newFilePath); //图片裁切 var thumbFilePath = newFilePath.Replace(Path.GetExtension(newFilePath), ".thumb" + Path.GetExtension(newFilePath)); ImageKit.MakeCenterThumbnail(newFilePath, thumbFilePath, 1602, 400); if (File.Exists(newFilePath)) { File.Delete(newFilePath); } context.Response.Write("{‘Success‘:‘true‘,‘FileName‘:‘" + saveFileName.Replace(".", ".thumb.") + "‘}"); } catch (Exception ex) { context.Response.Write("{‘Success‘:‘false‘,‘Message‘:‘"+ex.Message+"‘}"); } } else { context.Response.Write("{‘Success‘:‘false‘,‘Message‘:‘请选择要上传的文件‘}"); } } public bool IsReusable { get { return false; } } }
图片裁剪压缩的方法
public static class ImageKit { public static bool MakeCenterThumbnail(string origPath, string destPath, int width, int height) { try { using (Image image = Image.FromFile(origPath)) { int originalWidth = image.Width; int originalHeight = image.Height; double ratio = Math.Max((originalWidth / (double)width < originalHeight / (double)height) ? originalWidth / (double)width : originalHeight / (double)height, 1); var cutSize = new Size((int)Math.Round(width * ratio, 0), (int)Math.Round(height * ratio, 0)); int x = (int)Math.Round((double)(originalWidth - cutSize.Width) / 2, 0); int y = (int)Math.Round((double)(originalHeight - cutSize.Height) / 2, 0); ; var bitmap = new Bitmap(width, height); using (var graphics = Graphics.FromImage(bitmap)) { graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.Clear(Color.White); var destRect = new Rectangle(0, 0, width, height); var originalRect = new Rectangle(x, y, cutSize.Width, cutSize.Height); graphics.DrawImage(image, destRect, originalRect, GraphicsUnit.Pixel); } #region wjy20131004修改 // 以下代码为保存图片时,设置压缩质量 EncoderParameters encoderParams = new EncoderParameters(); long[] quality = new long[1]; quality[0] = 100; EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); encoderParams.Param[0] = encoderParam; //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象. ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICI = null; for (int i = 0;i < arrayICI.Length;i++) { if (arrayICI[i].FormatDescription.Equals("JPEG")) { jpegICI = arrayICI[i]; //设置JPEG编码 break; } } if (jpegICI != null) { bitmap.Save(destPath, jpegICI, encoderParams); } //bitmap.Save(destPath); #endregion } return true; } catch { return false; } } }
使用方法:
1,首先要添加JS引用
<script src="http://www.mamicode.com/Scripts/uploadify/v3.1/jquery.uploadify-3.1.min.js" type="text/javascript"></script>
<link href="http://www.mamicode.com/Scripts/uploadify/v3.1/uploadify1.css" rel="stylesheet" type="text/css" />
2,在页面中显示上传附件的按钮:
<div id="fileQueue">
</div>
<input type="file" name="uploadify" id="uploadify" />
<input type="hidden" name="BACKIMG" value=""/>
注意:隐藏控件BACKIMG是上传文件的路径,文件上传成功后要给它赋值,这样在表单提交成功后才可以根据图片路径读取到上传图片
3,如下所示Form表单
<form id="mainForm" method="post" action=‘@Url.Action(Model.Action)‘> </form>
提交时调用上传图片的方法
function submitbut() { var filecount = $(‘#fileQueue‘).find(‘div‘).length; if (filecount > 0) { $(‘#uploadify‘).uploadify(‘upload‘, ‘*‘); } else { $(‘#mainForm‘).submit(); } }
ASP.NET MVC中使用uploadify上传图片并按照规定大小压缩图片
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。