文章詳情頁(yè)
ASP.NET MVC實(shí)現(xiàn)單個(gè)圖片上傳、限制圖片格式與大小并在服務(wù)端裁剪圖片
瀏覽:193日期:2022-06-08 11:12:22
本篇,在ASP.NET MVC4下實(shí)現(xiàn)單個(gè)圖片上傳,具體功能包括:
- 1、在客戶端選擇圖片,并限制圖片的大小和格式
- 2、在客戶端上傳圖片,并顯示預(yù)覽圖
- 3、在服務(wù)端限制圖片的大小和格式
- 4、在服務(wù)端保存圖片時(shí),把圖片裁剪成某個(gè)固定尺寸
本篇源碼在:https://github.com/darrenji/FileUploadInMVC
實(shí)現(xiàn)的大致思路是:
- 客戶端限制圖片大小和格式,通過(guò)寫一個(gè)jQuery插件來(lái)實(shí)現(xiàn)
- 服務(wù)端實(shí)現(xiàn)圖片裁剪,通過(guò)使用ImageSize組件來(lái)實(shí)現(xiàn)
首先是一個(gè)用來(lái)承載上傳信息的類:
public class UploadFileResult {//帶后綴的名稱,比如xxx.jpgpublic string FileName { get; set; }//圖片的字節(jié)數(shù)public int Length { get; set; }//圖片的類型:image/jpegpublic string Type { get; set; }public bool IsValid { get; set; }public string Message { get; set; }//圖片的完整路徑:~/AjaxUpload/20141112_large.jpgpublic string FilePath { get; set; } }
在HomeController中,需要提供一個(gè)接收前端上傳文件并返回json格式的Action方法,還需要提供一個(gè)根據(jù)文件名刪除圖片的Action方法。
using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Web;using System.Web.Mvc;using ImageResizer;using MvcApplication10.Models;namespace MvcApplication10.Controllers{ public class HomeController : Controller {public ActionResult Index(){ return View();}//接收上傳圖片[HttpPost]public ActionResult UploadFile(){ //允許的圖片格式 var allowedExtensions = new[] { ".png", ".gif", ".jpg", ".jpeg" }; //返回給前臺(tái)的結(jié)果,最終以json返回 List<UploadFileResult> results = new List<UploadFileResult>(); //遍歷從前臺(tái)傳遞而來(lái)的文件 foreach (string file in Request.Files) {//把每個(gè)文件轉(zhuǎn)換成HttpPostedFileBaseHttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;//如果前臺(tái)傳來(lái)的文件為null,繼續(xù)遍歷其它文件if (hpf.ContentLength == 0 || hpf == null){ continue;}else{ if (hpf.ContentLength > 1024*1024) //如果大于規(guī)定最大尺寸 {results.Add(new UploadFileResult(){ FileName = "", FilePath = "", IsValid = false, Length = hpf.ContentLength, Message = "圖片尺寸不能超過(guò)1024KB", Type = hpf.ContentType}); } else {var extension = Path.GetExtension(hpf.FileName);if (!allowedExtensions.Contains(extension))//如果文件的后綴名不包含在規(guī)定的后綴數(shù)組中{ results.Add(new UploadFileResult() {FileName = "",FilePath = "",IsValid = false,Length = hpf.ContentLength,Message = "圖片格式必須是png、gif、jpg或jpeg",Type = hpf.ContentType });}else{ //給上傳文件改名 string date = DateTime.Now.ToString("yyyyMMddhhmmss"); //目標(biāo)文件夾的相對(duì)路徑 ImageSize需要的格式 string pathForSaving = Server.MapPath("~/AjaxUpload/"); //目標(biāo)文件夾的相對(duì)路徑 統(tǒng)計(jì)文件夾大小需要的格式 string pathForSaving1 = Server.MapPath("~/AjaxUpload"); //在根目錄下創(chuàng)建目標(biāo)文件夾AjaxUpload if (this.CreateFolderIfNeeded(pathForSaving)) {//保存小圖var versions = new Dictionary<string, string>();versions.Add("_small", "maxwidth=400&maxheight=250&format=jpg");//versions.Add("_medium", "maxwidth=200&maxheight=200&format=jpg");//versions.Add("_large", "maxwidth=600&maxheight=600&format=jpg");//保存各個(gè)版本的縮略圖foreach (var key in versions.Keys){ hpf.InputStream.Seek(0, SeekOrigin.Begin); ImageBuilder.Current.Build(new ImageJob(hpf.InputStream,pathForSaving + date + key, //不帶后綴名的圖片名稱new Instructions(versions[key]),false,//是否保留原圖true));//是否增加后綴}results.Add(new UploadFileResult(){ FileName = date + "_small" + ".jpg", FilePath = Url.Content(String.Format("~/AjaxUpload/{0}", date + "_small" + ".jpg")), IsValid = true, Length = hpf.ContentLength, Message = "上傳成功", Type = hpf.ContentType}); } } }} } return Json(new {filename = results[0].FileName,filepath=results[0].FilePath,isvalid=results[0].IsValid,length=results[0].Length,message=results[0].Message,type=results[0].Type });}//根據(jù)文件名刪除文件[HttpPost]public ActionResult DeleteFileByName(string smallname){ string pathForSaving = Server.MapPath("~/AjaxUpload"); System.IO.File.Delete(Path.Combine(pathForSaving, smallname)); return Json(new {msg = true });}//根據(jù)相對(duì)路徑在項(xiàng)目根路徑下創(chuàng)建文件夾private bool CreateFolderIfNeeded(string path){ bool result = true; if (!Directory.Exists(path)) {try{ Directory.CreateDirectory(path);}catch (Exception){ result = false;} } return result;} }}
在Home/Index.cshtml中,使用checkFileTypeAndSize.js插件來(lái)限制上傳圖片的大小和格式,使用FormData對(duì)象來(lái)接收?qǐng)D片文件并傳遞給服務(wù)端,客戶端接收到服務(wù)端json數(shù)據(jù)動(dòng)態(tài)創(chuàng)建表格行把預(yù)覽圖顯示出來(lái)。
@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml";}<style type="text/css"> #msg {color: red; }</style><form id="file_upload_form" method="post" enctype="multipart/form-data" action=""> <input name="file" id="file" size="27" type="file" /> <img src="~/images/ajax-loader.gif" id="indicator" /> <br /> <div id="imgArea"><table id="tbl"> <tbody> </tbody></table> </div> <div><span id="msg"></span> </div></form>@section scripts{ <script src="~/Scripts/checkFileTypeAndSize.js"></script> <script type="text/javascript">$(function() { $("#file").checkFileTypeAndSize({allowedExtensions: ["jpg","jpeg","gif","png"],maxSize: 1024, //最大允許1024KB,即1MBsuccess: function () { //顯示進(jìn)度提示 $("#indicator").css("display", "block"); //清空提示內(nèi)容 $("#msg").text(""); if ($("#fn").text().length > 0) {//刪除圖片deleteImg(); } //上傳文件數(shù)據(jù)準(zhǔn)備 var fd = new FormData(); fd.append("image", $("#file")[0].files[0]); $.ajax({url: "@Url.Action("UploadFile","Home")",type: "POST",data: fd,contentType: false,cache: false,processData: false,dataType: "json",success: function (data) { //隱藏進(jìn)度提示 $("#indicator").css("display", "none"); if (data.isvalid) {//$("#fileTemplate").tmpl(data).appendTo("#imgArea");createTableTr();$("#thumb").attr("src", data.filepath);$("#fn").text(data.filename); } else {$("#msg").text(data.message); }} }); },extensionerror: function () { //alert("允許的格式為:jpg,jpeg,gif,png"); $("#msg").text("允許的格式為:jpg,jpeg,gif,png"); return;},sizeerror: function () { //alert("最大尺寸1024KB,即1MB"); $("#msg").text("最大尺寸1024KB,即1MB"); return;} });});//刪除圖片function deleteImg() { $.ajax({cache: false,url: "@Url.Action("DeleteFileByName", "Home")",type: "POST",data: { smallname: $("#fn").text() },success: function (data) { if (data.msg) {$("#fn").parent().parent().remove(); }},error: function (jqXhr, textStatus, errorThrown) { alert("出錯(cuò)了 "" + jqXhr.status + "" (狀態(tài): "" + textStatus + "", 錯(cuò)誤為: "" + errorThrown + "")");} });}//創(chuàng)建表格function createTableTr() { var table = $("#tbl"); table.append("<tr><td><img id="thumb" /></td><td colspan="2"><span id="fn"></span></td></tr>");} </script>}
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
標(biāo)簽:
ASP.NET
相關(guān)文章:
1. ASP.NET MVC使用異步Action的方法2. ASP.NET MVC使用Boostrap實(shí)現(xiàn)產(chǎn)品展示、查詢、排序、分頁(yè)3. ASP.NET MVC獲取多級(jí)類別組合下的產(chǎn)品4. ASP.NET MVC通過(guò)勾選checkbox更改select的內(nèi)容5. ASP.NET MVC實(shí)現(xiàn)登錄后跳轉(zhuǎn)到原界面6. ASP.NET MVC使用Identity增刪改查用戶7. ASP.NET MVC實(shí)現(xiàn)區(qū)域或城市選擇8. ASP.NET MVC使用JSAjaxFileUploader插件實(shí)現(xiàn)單文件上傳9. 使用EF Code First搭建簡(jiǎn)易ASP.NET MVC網(wǎng)站并允許數(shù)據(jù)庫(kù)遷移10. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條
排行榜
