MVC图片上传、浏览、删除
1、存储配置信息
在web.config中,添加配置信息节点
<appSettings> <add key="UploadPath" value="D:\Uploads" /> </appSettings>
2、图片上传
html页面中
<div class="leftImage"> <input type="file" id="picAjax" class="customButton"/> <span id="uploadInfo"></span> <input type="button" id="submitPic" class="customButton" value="上传" /> </div> <div class="rightImage"> <img id="selImg" src="" alt="" /> </div>
js中,选择图片事件
var picString = ""; $("#picAjax").change(function (e) { var file = e.delegateTarget.files[0]; if (file.type == 'image/jpeg' || file.type == 'image/png') { $("#uploadInfo").text("图片格式正确,请点击提交按钮"); var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function (ret) { picString = reader.result; //预览图片 $("#selImg").attr({ "src": picString }); } } else { $("#uploadInfo").text("请上传jpg或png格式的图片!" ); } });
js中,上传图片事件
$("#submitPic").click(function () { if (picString != "") { $.ajax("../SavePicture", { type: "post", datatype: "json", data: { picString: picString, id: id }, error: function () { }, success: function (result) { if (result.suc == true) { $("#uploadInfo").text("图片上传成功!"); $("#ImageList").empty(); ReadPicture(); } } }); } });
C#中,保存图片
[HttpPost] public ActionResult SavePicture(string picString,string id) { var tmpArr = picString.Split(','); byte[] bytes = Convert.FromBase64String(tmpArr[1]); MemoryStream ms = new MemoryStream(bytes); ms.Write(bytes, 0, bytes.Length); var img = Image.FromStream(ms, true); var path = System.AppDomain.CurrentDomain.BaseDirectory; var imagesPath = System.IO.Path.Combine(path, @"Uploads\AgrCorporations\" + id + "\\"); if (!System.IO.Directory.Exists(imagesPath)) System.IO.Directory.CreateDirectory(imagesPath); string fileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo) + ".png"; var bitImage = GetThumbnailImage(img,400,300); bitImage.Save(imagesPath + fileName); bool isOk = true; string msg = imagesPath + fileName; return Json(new { suc = isOk, msg = msg }); } //图片压缩 public static Image GetThumbnailImage(Image srcImage, int width, int height) { Image bitmap = new Bitmap(width, height); Graphics g = Graphics.FromImage(bitmap); //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed; //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(srcImage, new Rectangle(0, 0, width, width), new Rectangle(0, 0, srcImage.Width, srcImage.Height), GraphicsUnit.Pixel); return bitmap; }
3、图片浏览和删除
html页面中
<div class="leftImage"> @Html.ListBoxFor(model => model.ImageList, (List<SelectListItem>)ViewBag.imageList, new { @class = "multipleList" }) <span id="deleteInfo"></span> <input type="button" id="deletePic" class="customButton" value="删除" /> </div> <div class="rightImage"> <img id="showImg" src="" alt="" /> </div>
js中,浏览和删除图片事件
@using Newtonsoft.Json; var vData =@Html.Raw(JsonConvert.SerializeObject(ViewData)); var id = vData["id"]; var imgName = null; $("#ImageList").on("change", function () { imgName = $("option:selected", this).val(); var imgUrl = "../../Uploads/AgrCorporations/" + id + "/" + imgName; $("#showImg").attr({ "src": imgUrl }); }); $("#deletePic").click(function () { if (imgName == null) { $("#deleteInfo").text("没有选择任何图片!"); } else { $.ajax("../DeletePicture", { type: "GET", datatype: "json", data: { id: id, imgName: imgName }, error: function () { }, success: function (result) { $("#deleteInfo").text(result.deleteInfo); $("#ImageList").empty(); $("#showImg").attr({ "src": "" }); ReadPicture(); } }); } }); function ReadPicture() { $.ajax("../ReadPicture", { type: "GET", datatype: "json", data: { id: id }, error: function () { }, success: function (data) { $.each(data, function (i,item) { $("<option></option>").val(item["Value"]).text(item["Text"]).appendTo($("#ImageList")); }) } }); }
C#中读取图片
public ActionResult ReadPicture(string id) { //图片列表 var path = System.AppDomain.CurrentDomain.BaseDirectory; var imagesPath = System.IO.Path.Combine(path, @"Uploads\AgrCorporations\" + id); var imageList = new List<string>(); if (System.IO.Directory.Exists(imagesPath)) { var files = System.IO.Directory.GetFiles(imagesPath, "*.*", SearchOption.TopDirectoryOnly).Where(s => s.EndsWith(".png") || s.EndsWith(".PNG") || s.EndsWith(".jpg") || s.EndsWith(".JPG")); var filesName = files.Select(p => System.IO.Path.GetFileName(p)); var imagesURL = filesName.Select(p => { return p; }); var imagesQuery = from name in imagesURL orderby name descending select name; if (imagesQuery.ToArray().Length > 0) { imageList = imagesQuery.ToList(); } } List<SelectListItem> ImageList = imageList.Select(p => new SelectListItem() { Text = p, Value = p }).ToList(); ViewBag.imageList = ImageList; return Json(ImageList, JsonRequestBehavior.AllowGet); }
C#中删除图片
public ActionResult DeletePicture(string id,string imgName) { var path = System.AppDomain.CurrentDomain.BaseDirectory; var imagesPath = System.IO.Path.Combine(path, @"Uploads\AgrCorporations\" + id + "\\"); var iFileName = imagesPath + imgName; FileInfo f = new FileInfo(iFileName); var deleteInfo = ""; try { f.Delete(); deleteInfo = "删除成功!"; } catch { } return Json(new { deleteInfo = deleteInfo}, JsonRequestBehavior.AllowGet); }