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;
}
}
}
}