一般处理程序上传文件

复制代码
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;

namespace CCOA.App.A_Demo.ashx
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            HttpPostedFile file = context.Request.Files["file1"];
            //是否上传文件
            if (file.ContentLength <= 0) //文件大小
            {
                context.Response.Write("请选择要上传的文件");
                return;
            }

            //上传文件大小检测
            if (file.ContentLength > 1024 * 1024)
            {
                context.Response.Write("上传文件大小不能超过1M");
                return;
            }

            //上传文件后缀名检测
            string filename = file.FileName; //文件绝对地址
            string suffix = Path.GetExtension(filename); //截取后缀
           // string suffix=filename.Substring(filename.LastIndexOf("."));
            if (suffix != ".jpg" & suffix != ".jpeg")
            {
                context.Response.Write("只允许上传jpg文件");
                return;
            }

             #region 保存文件
             //重命名:DateTime
            //Random ro = new Random();
            //filename = string.Format("{0}{1}{2}", DateTime.Now.ToString("yyyyMMddHHmmssff"), ro.Next(1000, 9999), suffix);

            //重命名:GUID(全球唯一标识符)推荐!!!
            filename = string.Format("{0}{1}", Guid.NewGuid().ToString("N"), suffix);

            //创建目录
             string dirPath = DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day;
             string dirFullPath = context.Server.MapPath("~/UploadFile/" + dirPath);

             //如果文件夹不存在,则先创建文件夹
             if (!Directory.Exists(dirFullPath))
             {
                 Directory.CreateDirectory(dirFullPath);
             }

             //将两个字符组合成一个路径
             string fileFullPath = Path.Combine(dirFullPath, filename);

             //保存文件
             file.SaveAs(fileFullPath);
             context.Response.Write("上传成功:" + fileFullPath);
             #endregion
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
复制代码

 

posted @   ~且听风吟~  阅读(63)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示