1.html页面 注意:form的enctype="multipart/form-data"
<form method="post" action="FileUp.ashx" enctype="multipart/form-data" > <input type="file" name="fileUp" /> <input type="submit" value="上传"/> </form>
2.一般处理程序后台处理
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string[] fileExtList = new string[] { ".jpg", ".png", ".img" }; HttpPostedFile file = context.Request.Files[0]; if (file.ContentLength>0) { //类型校验 string fileName = Path.GetFileName(file.FileName); string fileExt = Path.GetExtension(fileName); if (fileExtList.Contains(fileExt)) { //对上传文件重命名 fileName = Guid.NewGuid().ToString() + fileExt ; //将上传的文件放到不同的目录 string dir = "/ImageUpLoad/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/"; if (!Directory.Exists(context.Request.MapPath(dir))) { Directory.CreateDirectory(context.Request.MapPath(dir)); } fileName = dir + fileName; file.SaveAs(context.Request.MapPath(fileName)); //展示上传的图片 context.Response.Write("<html><body><img src=‘" + fileName + "‘></body></html>"); } else { context.Response.Write("只能上传图片文件"); } } else { context.Response.Write("请选择上传文件"); } }
时间: 2024-10-19 08:17:04