<%@ WebHandler Language="c#" Class="CommonUploadFile_WebHandler" Debug="true" %>
using System;
using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Configuration;

public class CommonUploadFile_WebHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState  //实现这个接口，意味着要实现该接口的两个方法： ProcessRequest和 IsReusable
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";  //响应数据类型context.Request.Files.Count > 0 && 
        if (context.Request.Files.Count > 0)
        {
            if (!Dcx.Common.VonleHelper.IsLogined())
            {
                context.Response.Write("0");  //返回最后结果
                context.Response.End();
                return;
            }
            string errMsg = "";
            int successCount = 0;
            int count = context.Request.Files.Count;
            int fileId = 0;
            if (count > 0)
            {
                int userId = Dcx.Common.VonleHelper.GetUserId_FromSession();
                string userName = Dcx.Common.VonleHelper.GetUserName_FromSession();
                int maxFileSize = 3 * 1024 * 1024;
                bool IsImg = false;

                string temp = context.Request.Form["IsImg"];
                if (!Dcx.Common.Utils.StrIsNullOrEmpty(temp) && Dcx.Common.Validator.IsValidInt(temp.Trim()) && Dcx.Common.TypeConverter.StrToInt(temp.Trim()) == 1)
                    IsImg = true;
                temp = context.Request.Form["appType"];
                int appType = 1;
                if (!Dcx.Common.Utils.StrIsNullOrEmpty(temp) && Dcx.Common.Validator.IsValidInt(temp.Trim()))
                    appType = Dcx.Common.TypeConverter.StrToInt(temp);
                string appTypeName = "diary";
                switch (appType)
                {
                    case 1:
                        appTypeName = "diary";
                        break;
                    case 2:
                        appTypeName = "mydisk";
                        break;
                    case 3:
                        appTypeName = "webIM";
                        break;
                    case 4:
                        appTypeName = "weibo";
                        break;
                    case 5:
                        appTypeName = "WMail";
                        break;
                    case 6:
                        appTypeName = "WLetter";
                        break;
                    case 7:
                        appTypeName = "WorkFlow";
                        break;
                    default:
                        appTypeName = "other";
                        break;
                }
                //允许上传文件类型
                string allowExt = null;
                if (IsImg)
                    allowExt = "gif|jpeg|jpg|bmp|png";
                string saveFileName = null;
                string saveFilePath = null;
                int fileSize = 0;
                DateTime date = DateTime.Now;//+ 1
                string newGuid = date.Year + (date.Month  < 10 ? "0" : "") + (date.Month) + (date.Day < 10 ? "0" : "") + date.Day + (date.Hour < 10 ? "0" : "") + date.Hour + (date.Minute < 10 ? "0" : "") + date.Minute + (date.Second < 10 ? "0" : "") + date.Second + "_";//Dcx.NewGuid(); Guid.NewGuid().ToString();
                try
                {
                    HttpPostedFile postedFile = context.Request.Files[0];   //得到上传文件的对象
                    if (postedFile.ContentLength > 0)
                    {
                        fileSize = postedFile.ContentLength;
                        string name = System.IO.Path.GetFileName(postedFile.FileName);
                        saveFilePath = "/UploadFiles/user/" + Dcx.BLL.Avatars.GetUserIdUrl(userId.ToString()) + "/" + appTypeName + "/Temp/";
                        saveFileName = saveFilePath + newGuid + name;
                        if (Dcx.Common.FileOperate.UpLoadFile(context, postedFile, maxFileSize, allowExt, saveFileName, ref  errMsg))
                        {
                            successCount = 1;
                        }
                        //生成图片的缩略图
                        string cmpsPath = context.Server.MapPath(saveFilePath + "cmps/" + newGuid + name);
                        SaveThumbnail(postedFile.InputStream, cmpsPath, 150);
                    }
                    else
                    {
                        errMsg += "您上传的文件是空的。";

                    }
                }
                catch (Exception e)
                {
                    errMsg += "" + e.Message;

                }
                if (successCount > 0)
                    context.Response.Write(errMsg + "*()^1" + "%$&" + saveFileName + "%$&" + newGuid + "%$&" + (fileSize / 1024) + "%$&" + fileId + "*()^2");
                else
                    context.Response.Write(errMsg + "*()^0" + "%$&" + errMsg + "*()^12"); //返回最后结果
            }
            context.Response.End();
        }
    }


    /// <summary>生成缩略图，并保存
    /// </summary>
    public static bool SaveThumbnail(Stream stm, string savePath, int width)
    {
        if (Dcx.Common.FileOperate.IsImg(System.IO.Path.GetExtension(savePath).ToLower()))
        {
            Bitmap oldImg = Dcx.Common.ImgUtil.IsImg(stm);
            if (oldImg != null)
                return SaveThumbnail(oldImg, savePath, 150);
        }
        return false;


    }

    /// <summary>生成缩略图，并保存
    /// </summary>
    public static bool SaveThumbnail(Bitmap oldImg, string savePath, int width)
    {
        Bitmap thumimg = Dcx.Common.ImgCmpsFactory.cmpsImgByWidth2(oldImg, width);

        FileInfo saveFile = new FileInfo(savePath);

        if (!System.IO.Directory.Exists(saveFile.DirectoryName ))
            System.IO.Directory.CreateDirectory(saveFile.DirectoryName);

        if (File.Exists(savePath))
        {
            File.SetAttributes(savePath, FileAttributes.Normal);
            File.Delete(savePath);
        }
        thumimg.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
        thumimg.Dispose();

        return true;

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

}
