asp.net上传文件

System.Web.HttpContext context = System.Web.HttpContext.Current;

//文件参数
if (context.Request.Files.Count == 0) { throw new Exception("未检测到文件!"); }
HttpPostedFile file = context.Request.Files[0];//只考虑一个文件的情况
string fileName = file.FileName;//文件名
string fileExtention = Path.GetExtension(file.FileName);//扩展名
int size = file.ContentLength;//文件大小

//文件外的其他参数
Dictionary<string, string> d = new Dictionary<string, string>();
for (int i = 0; i < context.Request.Form.Count; i++)
{
d.Add(context.Request.Form.AllKeys[i], context.Request.Form[i]);
}
string d1= d["d1"];//约定好传的参数 d1
string d2= d["d2"];

//上传到服务器
string path = "/files/" + type + "/" ; //IIS配置的路径 /files/
string dir = HttpContext.Current.Server.MapPath("/") + path;
if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); }
file.SaveAs(dir + fileName+ fileExtention);
----------------------------------------------------------------------------------------------------------------------------------------------------
问题:如果上传的文件超过4M,就会报错“超过了最大请求长度” (asp.net默认最大上传文件大小为4M,运行超时时间为90S)
解决方案:修改web.config文件的 httpRuntime
 <httpRuntime targetFramework="4.5.2" maxRequestLength="1048576" executionTimeout="3600" />

 

posted @ 2019-05-10 11:36  Zoe97  阅读(172)  评论(0编辑  收藏  举报