首页 > Web开发 > 详细

一般处理程序上传文件(html表单上传、aspx页面上传)

时间:2014-01-18 18:44:56      阅读:926      评论:0      收藏:0      [点我收藏+]

html 表单上传文件

       一般处理程序由于没有 apsx 页面的整个模型和控件的创建周期,而比较有效率。这里写一个用 html 表单进行文件上传的示例。

       1. 表单元素选用 <input type="file"> 控件。

       2. form 表单需要设置 enctype="multipart/form-data" 属性,请求报文体中数据格式也由键值对更改为数据头和数具体,并有随机边界符分割。

       3. 服务器端接收文件使用 Request.Files 属性。

       4. 使用 HttpPostedFile 的 SaveAs 方法保存文件(需转换成网站物理路径)。

 

 

<body>
    <form action="UploadFile.ashx" method="post" enctype="multipart/form-data">
    用户名:<input type="text" name="txtName" />
    <input type="file" name="fileUpload" />
    <input type="submit" value="上传文件" />
    </form>
</body>
public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/html";
    HttpServerUtility server = context.Server;
    HttpRequest request = context.Request;
    HttpResponse response = context.Response;
 
    HttpPostedFile file = context.Request.Files[0];
    if (file.ContentLength > 0)
    {
        string extName = Path.GetExtension(file.FileName);
        string fileName = Guid.NewGuid().ToString();
        string fullName = fileName + extName;
        
        string imageFilter = ".jpg|.png|.gif|.ico";// 随便模拟几个图片类型
        if (imageFilter.Contains(extName.ToLower()))
        {
            string phyFilePath = server.MapPath("~/Upload/Image/") + fullName;
            file.SaveAs(phyFilePath);
            response.Write("上传成功!文件名:" + fullName + "<br />");
            response.Write(string.Format("<img src=‘Upload/Image/{0}‘/>", fullName));                
        }
    }
}

一般处理程序上传文件(html表单上传、aspx页面上传)

原文:http://www.cnblogs.com/SkySoot/p/3525139.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!