<%@ WebHandler Language="C#" Class="Upload" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.IO;
using System.Globalization;
/// <summary>
/// 文件名:Upload
/// 文件功能描述:上传的管理操作以及判断逻辑处理
/// 版权所有:Copyright (C) liangjw
/// 创建标识:2013.07.18 
/// 修改描述:
/// </summary>
public class Upload : IHttpHandler
{
    private HttpContext context;

    public void ProcessRequest(HttpContext context)
    {
        //文件保存目录路径
        string saveUrl = "/upfile/attachment";

        //定义允许上传的文件扩展名
        Hashtable extTable = new Hashtable();
        extTable.Add("image", Utility.GetAppSetting("Attach_Image"));
        extTable.Add("flash", Utility.GetAppSetting("Attach_Flash"));
        extTable.Add("media", Utility.GetAppSetting("Attach_Media"));
        extTable.Add("file", Utility.GetAppSetting("Attach_File"));

        //最大文件大小
        int maxSize = 102400000;
        this.context = context;

        var imgFile = context.Request.Files["imgFile"];
        if (imgFile == null)
        {
            showError("请选择文件。");
        }

        string dirPath = context.Server.MapPath(saveUrl);
        if (!Directory.Exists(dirPath))
        {
            showError("上传目录不存在。");
        }

        string fileName = imgFile.FileName;
        string fileExt = Path.GetExtension(fileName).ToLower();

        string dirName = context.Request.QueryString["dir"];
        if (string.IsNullOrEmpty(dirName))
        {
            List<string> fileExts = new List<string>();
            foreach (DictionaryEntry item in extTable)
            {
                if (Array.IndexOf(item.Value.ToString().Split(','), fileExt.Substring(1).ToLower()) != -1)
                {
                    dirName = item.Key.ToString();
                    break;
                }
                fileExts.AddRange(item.Value.ToString().Split(','));
            }
            if (string.IsNullOrEmpty(dirName))
            {
                showError("上传文件扩展名是不允许的扩展名。\n只允许" + string.Join(",", fileExts.Distinct()) + "格式。");
            }
        }
        else
        {
            if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(((string)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((string)extTable[dirName]) + "格式。");
            }
        }

        if (!extTable.ContainsKey(dirName))
        {
            showError("目录名不正确。");
        }

        if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
        {
            showError("上传文件大小超过限制。");
        }

        //创建文件夹
        dirPath += dirName + "/";
        saveUrl += dirName + "/";
        if (!Directory.Exists(dirPath))
        {
            Directory.CreateDirectory(dirPath);
        }
        string ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
        dirPath += ymd + "/";
        saveUrl += ymd + "/";
        if (!Directory.Exists(dirPath))
        {
            Directory.CreateDirectory(dirPath);
        }

        string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
        string filePath = dirPath + newFileName;

        imgFile.SaveAs(filePath);

        string fileUrl = saveUrl + newFileName;

        context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
        context.Response.Write("{\"error\":0,\"url\":\"" + fileUrl + "\"}");
        context.Response.End();
    }

    private void showError(string message)
    {
        context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
        context.Response.Write("{\"message\":\"" + putStr(message) + "\",\"error\":1}");
        context.Response.End();
    }

    private string putStr(string str)
    {
        string returnStr = "";
        for (int i = 0; i < str.Length; i++)
        {
            switch (str[i])
            {
                case '\b':
                    {
                        returnStr += @"\b";
                        continue;
                    }
                case '\t':
                    {
                        returnStr += @"\t";
                        continue;
                    }
                case '\n':
                    {
                        returnStr += @"\n";
                        continue;
                    }
                case '\f':
                    {
                        returnStr += @"\f";
                        continue;
                    }
                case '\r':
                    {
                        returnStr += @"\r";
                        continue;
                    }
                case '"':
                case '\\':
                    {
                        returnStr += '\\';
                        returnStr += str[i];
                        continue;
                    }
            }
            if ((str[i] >= ' ') && (str[i] <= '~'))
            {
                returnStr += str[i];
            }
            else
            {
                IntToHex(str[i], hex_seq);
                returnStr += @"\u";
                returnStr += new string(hex_seq);
            }
        }
        return returnStr;
    }
    private char[] hex_seq = new char[4];
    private void IntToHex(int n, char[] hex)
    {
        for (int i = 0; i < 4; i++)
        {
            int num = n % 0x10;
            if (num < 10)
            {
                hex[3 - i] = (char)(0x30 + num);
            }
            else
            {
                hex[3 - i] = (char)(0x41 + (num - 10));
            }
            n = n >> 4;
        }
    }

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