控制器中
- public ActionResult FileUP(HttpPostedFileBase file)
- {
- var files = Request.Files;
- if (files != null && files.Count > 0)
- {
- #region 执行多个文件上传
- for (int i = 0; i < files.Count; i++)
- {
- HttpPostedFileBase fileitem = files[i];
- //判定文件的大小
- string strExtension = Path.GetExtension(fileitem.FileName);
- double dFileSize = fileitem.ContentLength;
- if (dFileSize > 5242880)//1024*1024*5)
- {
- return Content("<script>alert('" + fileitem.FileName + "文件大于5MB')</script>");
- }
- else
- {
- //创建文件
- string filePath = "~/images/Student/";
- Directory.CreateDirectory(Server.MapPath(filePath));
- //创建唯一的文件名
- string fileName = Guid.NewGuid().ToString();
- string fFullDir = filePath + fileName + strExtension;
- fileitem.SaveAs(Server.MapPath(fFullDir));
- }
- }
- #endregion
- }
- else
- {
- #region 执行单个文件上传
- if (file != null)
- {
- //可以判断它的大小格式
- //创建文件夹
- string filePath = "~/images/Student/";
- Directory.CreateDirectory(Server.MapPath(filePath));
- //string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
- string fileName = Guid.NewGuid().ToString();
- file.SaveAs(Server.MapPath(filePath + fileName + ".png"));
- return Content("<script>alert('上传成功!');location.href="
- + Url.Content(filePath) + "</script>");
- }
- #endregion
- }
- return View();
- }