zoukankan      html  css  js  c++  java
  • 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 }
     
  • 相关阅读:
    考研打卡_Day018
    如何使用python中的pymysql操作mysql数据库
    Linux系统目录结构和常用目录主要存放内容的说明
    MySQL基础入门使用和命令的使用
    Python中property属性的概论和使用方法
    如何有效的优化自己的网站访问速度
    机器学习中的特征工程学习
    ffmpeg中c语言sdk多媒体互转主要使用的api
    FFmpeg使用c语言sdk实现打印视频的信息
    ffmpeg使用C语言sdk实现抽取视频中的视频数据
  • 原文地址:https://www.cnblogs.com/yaoxc/p/3104017.html
Copyright © 2011-2022 走看看