前台代码如下
@{ Layout = null; } <!DOCTYPE html> <html> <head> <title>Index</title> <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script> <script type="text/javascript"> var times = 1; $("#add").click(function () { var fileNmae = "FileUpLoad" + n; $("#divdivfile").append("<input type="file" name="" + fileNmae + "" />"); times++; }); </script> </head> <body> <div> @using (Html.BeginForm("UpLoad", "UpdateLoad", FormMethod.Post, new { enctype="multipart/form-data"})) { <div id="divfile"> <input type="file" name="FileUpload" /> </div> <input type="button" id="add" value="增加" /> <input type="submit" id="Submit" value="上传" /> } </div> </body> </html>
首先判断上传的文件是否合法
public enum FileTypeExtension { GIF = 7173, PNG = 13780, JPG = 255216, } public class FileUploadCommon { /// <summary> /// 主要用于判断上传的特定文件是否附合特定后缀名的限制 /// </summary> /// <param name="fu">上传的文件对象</param> /// <param name="fileEx">系统允许上传的文件的类型</param> /// <returns>true:代表通过验证,false:代表没有通过验证</returns> public static bool IsAllowedExtension(HttpPostedFileBase fu, FileTypeExtension[] fileEx) { int contentLength = fu.ContentLength; byte[] buffer = new byte[contentLength]; fu.InputStream.Read(buffer, 0, contentLength); MemoryStream input = new MemoryStream(buffer); BinaryReader reader = new BinaryReader(input); string s = ""; try { s = reader.ReadByte().ToString(); s = s + reader.ReadByte().ToString(); } catch { } reader.Close(); input.Close(); foreach (FileTypeExtension extension in fileEx) { if (int.Parse(s) == Convert.ToInt32(extension)) { return true; } } return false; } }
后台代码 分为 单个上传和批量上传,注示部份为批量上传
[HttpPost] [ValidateInput(false)] public ActionResult UpLoad(FormModel model) { FileTypeExtension[] fileTypeArr = { FileTypeExtension.GIF, FileTypeExtension.JPG, FileTypeExtension.PNG }; // 单个上传 try { if (Request.Files != null && Request.Files.Count > 0 && Request.Files[0].ContentLength > 0) { string fileType = Request.Files[0].FileName.Substring(Request.Files[0].FileName.LastIndexOf(".")); // 获取文件类型 Stream fileStream = Request.Files[0].InputStream; bool fileOk = FileUploadCommon.IsAllowedExtension(Request.Files[0], fileTypeArr); // 判断上传的文件是否合法 if (fileOk && Request.Files[0].ContentLength / 1024 < 1024) // 判断合法 及 文件大小是否合法 { string path = Server.MapPath("/Content/FileUpdateLoad/"); string fileName = Path.GetFileNameWithoutExtension(Request.Files[0].FileName) + DateTime.Now.ToString("yyyyMMddHHmmss") + fileType; Request.Files[0].SaveAs(Path.Combine(path, fileName)); return RedirectToAction("Index", "UpdateLoad");
} else ViewBag.Error = "文件过大或格式不正确"; } else ViewBag.Error = "上传文件失败,可能您未选择上传文件"; } catch (Exception ex) { ViewBag.Error = "上传文件失败,原因如下:" + ex.Message; } //foreach (string upload in Request.Files) // 如果是批量上传 //{ // if (upload != null && Request.Files[upload].ContentLength > 0) // { // string fileType = Request.Files[upload].ContentType; // 获取文件类型 // Stream fileStream = Request.Files[upload].InputStream; // bool fileOk = FileUploadCommon.IsAllowedExtension(Request.Files[upload], fileTypeArr); // 判断上传的文件是否合法 // if (fileOk && Request.Files[upload].ContentLength / 1024 < 1024) // 判断合法 及 文件大小是否合法 // { // string path = Server.MapPath("/Content/FileUpdateLoad/"); // string fileName = Path.GetFileNameWithoutExtension(Request.Files[upload].FileName) + DateTime.Now.ToString("yyyyMMddHHmmss") + fileType; // Request.Files[upload].SaveAs(Path.Combine(path, fileName)); // } // else // ViewBag.Error = "文件过大或格式不正确"; // } // else continue; //} return View(model);
}
还可以通过以下方式:
[HttpPost] [ValidateInput(false)] public ActionResult UpdateLoad() { FileTypeExtension[] fileTypeArr = { FileTypeExtension.GIF, FileTypeExtension.JPG, FileTypeExtension.PNG }; // 单个上传 try { if (Request.Files != null && Request.Files.Count > 0 && Request.Files[0].ContentLength > 0) { HttpRequest request = System.Web.HttpContext.Current.Request; HttpFileCollection FileCollect = request.Files; if (FileCollect.Count > 0&& FileCollect[0].ContentLength>0) //如果集合的数量大于0 { //foreach (string str in FileCollect) //{ // HttpPostedFile FileSave = FileCollect[str]; //用key获取单个文件对象HttpPostedFile // string imgName = DateTime.Now.ToString("yyyyMMddhhmmss"); // string imgPath = "/" + imgName + FileSave.FileName; //通过此对象获取文件名 // string AbsolutePath = Server.MapPath(imgPath); // FileSave.SaveAs(AbsolutePath); //将上传的东西保存 // Response.Write("<img src='" + imgPath + "'/>"); //} HttpPostedFile FileSave = FileCollect[0]; //用key获取单个文件对象HttpPostedFile string fileName = Path.GetFileName(FileSave.FileName); string imgName = DateTime.Now.ToString("yyyyMMddhhmmss") + FileSave.FileName; bool fileOk = FileUploadCommon.IsAllowedExtension(Request.Files[0], fileTypeArr); // 判断上传的文件是否合法 if (fileOk && FileSave.ContentLength / 1024 < 1024) // 判断合法 及 文件大小是否合法 { string AbsolutePath = Server.MapPath("/Content/FileUpdateLoad/" + imgName); FileSave.SaveAs(AbsolutePath); //将上传的东西保存 //int fileLength = FileSave.ContentLength; //Byte[] fileByteArr = new Byte[fileLength]; //Stream fileStream = FileSave.InputStream; // 创建文件读取流 //fileStream.Read(fileByteArr, 0, fileLength); //localhost.WebService1 myService = new localhost.WebService1(); //myService.SaveFile(fileByteArr, fileLength, fileName); } } } } catch (Exception ex) { TempData["UploadError"] = "上传文件失败,原因如下:" + ex.Message; } return RedirectToAction("Index"); }
关于配置文件 限制上传文件大小 和上传时间
<httpRuntime executionTimeout="5000" maxRequestLength="2048000" useFullyQualifiedRedirectUrl="false"/> </system.web>