mvc多个文件上传和单个文件上传

来源:互联网 发布:爱网络聊天的男人 编辑:程序博客网 时间:2024/05/23 00:14

控制器中

[csharp] view plain copy
  1. public ActionResult FileUP(HttpPostedFileBase file)  
  2. {  
  3.    var files = Request.Files;  
  4.     if (files != null && files.Count > 0)  
  5.     {  
  6.         #region  执行多个文件上传  
  7.         for (int i = 0; i < files.Count; i++)  
  8.         {  
  9.             HttpPostedFileBase fileitem = files[i];  
  10.             //判定文件的大小  
  11.             string strExtension = Path.GetExtension(fileitem.FileName);  
  12.             double dFileSize = fileitem.ContentLength;  
  13.             if (dFileSize > 5242880)//1024*1024*5)  
  14.             {  
  15.                 return Content("<script>alert('" + fileitem.FileName + "文件大于5MB')</script>");  
  16.             }  
  17.             else  
  18.             {  
  19.                 //创建文件  
  20.                 string filePath = "~/images/Student/";  
  21.                 Directory.CreateDirectory(Server.MapPath(filePath));  
  22.                 //创建唯一的文件名  
  23.                 string fileName = Guid.NewGuid().ToString();  
  24.                 string fFullDir = filePath + fileName + strExtension;  
  25.                 fileitem.SaveAs(Server.MapPath(fFullDir));  
  26.             }  
  27.         }  
  28.         #endregion  
  29.     }  
  30.     else  
  31.     {  
  32.         #region 执行单个文件上传  
  33.         if (file != null)  
  34.         {  
  35.             //可以判断它的大小格式  
  36.             //创建文件夹  
  37.             string filePath = "~/images/Student/";  
  38.             Directory.CreateDirectory(Server.MapPath(filePath));  
  39.             //string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");  
  40.             string fileName = Guid.NewGuid().ToString();  
  41.             file.SaveAs(Server.MapPath(filePath + fileName + ".png"));  
  42.             return Content("<script>alert('上传成功!');location.href="  
  43.                 + Url.Content(filePath) + "</script>");  
  44.         }  
  45.         #endregion  
  46.     }  
  47.     return View();