HttpHandler实现单个文件上传

一、浏览器端
     1.表单元素使用 文件选择框<input type="file"/> 控件。
    2.表单设置enctype
 二、服务器端
     1.服务器接收客户端上传的文件使用Request.Files属性
     2.使用HttpPostedFile的SaveAs方法将图片保存在服务器
 
代码实现:
 模板文件ImageUpLoad.htm
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 
 3 <html xmlns="http://www.w3.org/1999/xhtml">
 4 <head>
 5     <title></title>
 6 </head>
 7 <body>
 8 <form action ='' method = "post" enctype="multipart/form-data">
 9 //注意:包含name属性的input元素数据才会提交到服务器
10 <input type="file" name='Upload'/>
11 <input type="hidden" name="isPostBack" value="1" />
12 <input type="submit" name="上传" />
13 </form>
14 </body>
15 </html>

.ashx文件

 1 <%@ WebHandler Language="C#" Class="UploadImg" %>
 2 
 3 using System;
 4 using System.Web;
 5 
 6 public class UploadImg : IHttpHandler {
 7     
 8     public void ProcessRequest (HttpContext context) {
 9         //context.Response.ContentType = "text/plain";
10         //context.Response.Write("Hello World");
11         string ispostback=context.Request.Form["isPostBack"];
12         string path = context.Server.MapPath("ImageUpLoad.htm");
13         string strHTML = System.IO.File.ReadAllText(path);
14         if (!string.IsNullOrEmpty(ispostback))
15         {
16             if (context.Request.Files.Count > 0)
17             {
18                 //获取上传的第一个文件
19                 HttpPostedFile file = context.Request.Files[0];
20                 //将文件保存在服务器
21                 file.SaveAs(context.Server.MapPath("Image/")+file.FileName);
22                 context.Response.Write("上传成功。。。"+file.FileName);
23             }
24         }
25         else {
26             context.Response.Write(strHTML); 
27         }
28     }
29  
30     public bool IsReusable {
31         get {
32             return false;
33         }
34     }
35 
36 }
 
原文地址:https://www.cnblogs.com/yaoxc/p/3104017.html