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/archive/2013/05/28/3104017.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值