簡介
這篇文章主要介紹下如何在asp.net mvc項目中使用uploadify,並實現簡單的圖片比例縮放保存。文章中參考整理了一些網上的資源,如果有問題,歡迎指出。
uploadify介紹
uploadify新版對參數進行了一些改動
本文使用的是v3.2版本,如果有使用以前版本的,請參照在asp.net mvc中使用Uploadify上傳文件,不了解uploadify請參照JQuery上傳插件Uploadify使用詳解
uploadify部分API介紹:
Options
swf :uploadify.swf 文件的相對路徑
uploader :后台處理程序的相對路徑
queueID :文件隊列的ID,該ID與存放文件隊列的div的ID一致。
auto :true直接上傳,false需要調用相關方法(見下upload)才能上傳
multi :true允許多文件上傳,false單文件上傳
formData :通過form傳遞額外的參數
Events
onUploadSuccess :每上傳成功一次回調函數
Methods
settings :返回或更新一個uploadify實例的設置屬性
upload :上傳文件隊列中特定的文件或者全部
Note: cancelImg這個上傳動畫中的取消按鈕圖片參數沒有了,我是直接在uploadify.css里面改的
以上參數是本文代碼需要用到的,其它參數介紹可參照官方文檔
在Mvc4中使用uploadify
在標題頭中引入js和css文件
<script type="text/javascript" src="~/Scripts/jquery-2.0.0.min.js"></script> <script type="text/javascript" src="~/Scripts/uploadify/jquery.uploadify.js"></script> <link href="~/Scripts/uploadify/uploadify.css" rel="stylesheet" type="text/css" />
在View里添加控件標簽
<div> @Html.Label("H:") @Html.TextBox("h", "", new { @class = "intonly" }) //輸入要保存為的圖片高度 @Html.Label("*required an integer", new { id = "hval", style = "display:none;color:red;" }) </div> <div> @Html.Label("W:") @Html.TextBox("w", "", new { @class = "intonly" }) //輸入要保存為的圖片寬度 @Html.Label("*required an integer", new { id = "wval", style = "display:none;color:red;" }) </div> <input type="file" name="uploadify" id="uploadify" /> <div id="fileQueue"></div> //上傳的文件隊列顯示標簽 <a href="javascript:void(0)" id="uploadstart">Upload Files</a> //使用a標簽控制何時上傳 @Html.TextBox("Filepath") //保存保存的圖片路徑集合 <br /> <img id="fileimg" src="" alt="無圖片" /> //用於顯示其中的一個圖片查看效果
給File控件加上js
$("#uploadify").uploadify({ 'swf': '@Url.Content("~/Scripts/uploadify/uploadify.swf")', //此處內部已經實現阻止緩存 'uploader': '@Url.Action("Uploadify")', //post到內部uploadify方法. Note:此處不能以查詢字符串的形式傳遞參數 'queueID': 'fileQueue', //綁定文件隊列ID 'auto': false, //禁止自動上傳 'multi': true, //允許多文件上傳 'onUploadSuccess': function (file, data, response) { var s = data; var filepath = $("#Filepath").val(); var filepaths = filepath + ";" + data; //每次文件上傳成功后以分號拼接圖片路徑 if (filepath.trim() == "") { //如果只有一個圖片不用分號 filepaths = data; } $("#Filepath").val(filepaths); $("#fileimg").attr("src", filepaths.split(";")[0]); //顯示第一個上傳的圖片 } });
說明:上面uploader參數請求的是MVC的一個方法,這里是當前controller的uploadify方法(我的路由是默認的"{controller}/{action}/{id}");
加上驗證與限制,傳遞額外的參數
$(function () { $(".intonly").keyup(function () { this.value = this.value.replace(/[^0-9\.]/g, ''); //使高寬輸入框只能輸入小數與整數 }); $("#uploadstart").click(function () { //控制上傳的a標簽的點擊事件 if ($("#fileQueue").html().trim() == "") { //驗證沒有文件上傳的情況 alert("請先選擇上傳文件"); return; } var h = $("#h").val(); var w = $("#w").val(); if (h.trim() == "") { //對高度框無值的情況進行提示 $("#hval").css("display", "inline"); return; } else { $("#hval").css("display", "none"); } if (w.trim() == "") { //對寬度框無值的情況進行提示 $("#wval").css("display", "inline"); return; } else { $("#wval").css("display", "none"); } $(".intonly").attr({ "disabled" : "true" }); //驗證通過后使高寬無法輸入並置灰 $(".intonly").css("background-color", "#EFEEEF"); $("#uploadify").uploadify('settings', 'formData', { 'h' : $("#h").val(), 'w' : $("#w").val() }); //通過設置settings的formData值傳遞額外的參數到Action $("#uploadify").uploadify('upload', '*'); //上傳文件隊列中的所有文件 // Note:此處我想和上面使用一個uploadify,但郁悶的是沒找見,也沒試出來如何同時使用upload和settings作參數 }); });
C#按照比例縮放圖片算法
此法是參照外國一個網站上的(原文鏈接),只能按比例縮放圖片,難免有些不盡人意,大家如果還有什么比較好的方法,還請指教。
private static Image resizeImage(Image imgToResize, Size size) { int sourceWidth = imgToResize.Width; int sourceHeight = imgToResize.Height; float nPercent = 0; float nPercentW = 0; float nPercentH = 0; nPercentW = ((float)size.Width / (float)sourceWidth); nPercentH = ((float)size.Height / (float)sourceHeight); if (nPercentH < nPercentW) nPercent = nPercentH; else nPercent = nPercentW; int destWidth = (int)(sourceWidth * nPercent); int destHeight = (int)(sourceHeight * nPercent); Bitmap b = new Bitmap(destWidth, destHeight); Graphics g = Graphics.FromImage((Image)b); g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(imgToResize, 0, 0, destWidth, destHeight); g.Dispose(); return (Image)b; }
在控制器方法里對圖片進行處理
[HttpPost]
public ActionResult Uploadify(int h=300, int w=300) //Note:此處要想通過方法參數獲取form值必須有默認值,否則會報錯 { string filePath = ""; foreach (string item in Request.Files) { HttpPostedFileBase postFile = Request.Files[item]; if (postFile.ContentLength == 0) continue; string newFilePath = Request.ApplicationPath + "UploadFile/" + string.Format("{0:yyyyMMdd}", DateTime.Today); if (!System.IO.Directory.Exists(Server.MapPath(newFilePath))) //在UploadFile下創建當天的文件夾 { System.IO.Directory.CreateDirectory(Server.MapPath(newFilePath)); } string file = newFilePath + "/" + string.Format("{0:hhmmss}", DateTime.Now) +"_"+ System.Guid.NewGuid() + "." + postFile.FileName.Split('.').Last(); filePath = file; Image imageFile = resizeImage(Image.FromStream(postFile.InputStream, true, true), new Size { Height = h, Width = w }); imageFile.Save(Server.MapPath(file)); } return Content(filePath); //將文件路徑Response }
完成后效果圖如下
結束語
至此,本次的uploadify使用就結束了。我是物理系畢業的,畢業快一年了,入道也快一年了,基礎什么的都比較差,正在努力向大牛們學習。自從接觸了博客園,看到了Fish Li這樣的大牛,就一直有了寫博客的想法,而這也是第一次寫,如果有什么問題,歡迎指正!最后,我還想感謝下經常寫博客的TimYang,從他的博客里感受到了強大的正能量。謝謝博客園這個平台。
附:源碼下載