简单的MVC多图上传实例

MVC多图上传

public class HomeController : Controller { ///

/// 参数pic为图片路径,多个图片用,间隔 这里为了直观写在参数里 实际应该从数据库读取 /// /// /// public ActionResult Index(string pic) { var html = "删除"; if (!string.IsNullOrEmpty(pic)) { if (pic.IndexOf(",") > 0) { string[] arrWeb = pic.Split(','); foreach (var item in arrWeb) { ViewBag.PicStr1 = String.Format(html, "/images/" item, "pic1", item); } } else { ViewBag.PicStr1 = String.Format(html, "/images/" pic, "pic1", pic); } } return View(); } /// /// 图片实体类 /// public class UploadFiles { //图片名字 public string FileName { get; set; } //图片路径 public string FilePath { get; set; } //图片大小 public string FileSize { get; set; } } /// /// 获取文件大小 /// /// /// private string GetFileSize(long bytes) { long kblength = 1024; long mbLength = 1024 * 1024; if (bytes < kblength) return bytes.ToString() "B"; if (bytes < mbLength) return decimal.Round(decimal.Divide(bytes, kblength), 2).ToString() "KB"; else return decimal.Round(decimal.Divide(bytes, mbLength), 2).ToString() "MB"; } /// /// 图片上传 /// /// public JsonResult Upload() { HttpFileCollection files = System.Web.HttpContext.Current.Request.Files; if (files.Count == 0) return Json("Faild", JsonRequestBehavior.AllowGet); List lf = new List(); for (int i = 0; i < files.Count; i ) { MD5 md5Hasher = new MD5CryptoServiceProvider(); /*计算指定Stream对象的哈希值*/ byte[] arrbytHashValue = md5Hasher.ComputeHash(files[i].InputStream); /*由以连字符分隔的十六进制对构成的String,其中每一对表示value中对应的元素;例如“F-2C-4A”*/ string strHashData = System.BitConverter.ToString(arrbytHashValue).Replace("-", ""); string FileEextension = Path.GetExtension(files[i].FileName); string uploadDate = DateTime.Now.ToString("yyyyMMdd"); string virtualPath = string.Format("/images/{1}{2}", uploadDate, strHashData, FileEextension); string fullFileName = Server.MapPath(virtualPath); //创建文件夹,保存文件 string path = Path.GetDirectoryName(fullFileName); Directory.CreateDirectory(path); if (!System.IO.File.Exists(fullFileName)) { files[i].SaveAs(fullFileName); } string fileSize = GetFileSize(files[i].ContentLength); UploadFiles uf = new UploadFiles(); uf.FileName = strHashData FileEextension; uf.FilePath = virtualPath; uf.FileSize = fileSize; lf.Add(uf); } return Json(new { listPic = lf }, "text/html", JsonRequestBehavior.AllowGet); } }