文件上传之 HttpPostedFile
HttpPostedFile类,提供对客户端已上载的单独文件的访问。
公共属性如下:
SaveAs()方法,用于保存上传文件的内容。
用法为:
#region 文件上传 /// <summary> /// 检查上传文件格式是否正确 /// </summary> /// <param name="fileExtension">文件扩展名</param> /// <returns></returns> public static bool checkFileExtension(string fileExtension) { string[] extensionArr = { ".doc", ".txt", ".pdf", ".rar", ".zip", ".docx", ".doc", ".ppt", ".png", ".gif", ".jpg", ".jpeg" }; for (int i = 0; i < extensionArr.Length; i++) { if (fileExtension == extensionArr[i]) { return true; } } return false; } /// <summary> /// 上传文件 /// </summary> /// <param name="fileName">文件名称</param> /// <returns></returns> public static string fileUpload(string fileName) { string fileNewName = String.Empty; if (fileName.Length > 0) { string fileExtension = Path.GetExtension(fileName).ToLower(); if (checkFileExtension(fileExtension)) { fileNewName = DateTime.Now.ToString("yyyyMMddhhmmss") + fileExtension; HttpPostedFile file = HttpContext.Current.Request.Files[0]; file.SaveAs(HttpContext.Current.Server.MapPath("~/upload/" + fileNewName)); } } return fileNewName; } #endregion
上传到服务器文件的大小有限制时,可以在webconfig中设置如下
<configuration> <system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" maxRequestLength="1024000" executionTimeout="3000000"/> </system.web> <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="1048576000"></requestLimits> </requestFiltering> </security> </system.webServer> </configuration>
关于设置文件大小的属性,参考链接:http://blog.163.com/shankao@126/blog/static/13154442720144126441656/