ASP 文件上传

89 篇文章 0 订阅


html页面:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <!--enctype="multipart/form-data":如果要上传文件必须加上该属性,指定相应的编码。只有这样用户选择的文件数据(文件流)才会放在请求报文中,发送给服务器。表单中的其它表单元素(文本框等),也会发送到服务端,但是格式也变了,但是在服务端还是按照以前的方式进行接收-->
    <!--如果表单不需要上传文件就不用加enctype--->
    <form method="post" action="ProcessFileUp.ashx" enctype="multipart/form-data">
        <input type="file" name="fileUp"/>
        <input type="text" name="txtName" />

        <input type="submit" value="上传" />

    </form>
</body>
</html>
服务器端接收数据(ProcessFileUp.ashx.cs):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace Project.WebApp._2015_5_27
{
    /// <summary>
    /// ProcessFileUp 的摘要说明
    /// </summary>
    public class ProcessFileUp : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
           HttpPostedFile file=context.Request.Files[0];//获取上传的文件.
           if (file.ContentLength>0)
           {
               //对上传的文件类型进行校验。
               string fileName =Path.GetFileName(file.FileName);//从全路径文件名(绝对路径)中获取上传文件的名称及扩展名。
               string fileExt = Path.GetExtension(fileName);//获取用户上传的文件扩展名。
               if (fileExt == ".jpg" || fileExt == ".png")
               {
                   //1.对上传文件进行重命名
                   string newfileName = Guid.NewGuid().ToString();  //全球唯一的文件名
                   //2:将上传的文件放在不同的目录下面
                   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));
                   }

                   string fullDir = dir + newfileName + fileExt; //文件存放的完整路径。
                   file.SaveAs(context.Request.MapPath(fullDir));

                 //  file.SaveAs(context.Request.MapPath("/ImageUpload/"+fileName));//完成文件的保存。这种方式 文件名容易冲突。
                   context.Response.Write("<html><body><img src='"+fullDir+"'/></body></html>");
               }
               else
               {
                   context.Response.Write("只能上传图片文件");
               }
           }
           else
           {
               context.Response.Write("请选择上传文件");
           }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值