using System;
using System.Collections;
using System.IO;
using System.Web;
using System.Web.Mvc;
using FHT.Core.InfrastructureServiceInterfaces.InfrastructureServices;
using FHT.Utilities;
using LitJson;
using System.Drawing;
namespace FHT.Core.Web.Scripts.plugins.kindeditor
{
///
/// upload_json 的摘要说明
///
public class upload_json : IHttpHandler
{
private HttpContext context;
private readonly IFileUploadInfrastructureService _fileUploadInfrastructureService;
///
/// 文件上传
///
public upload_json()
{
_fileUploadInfrastructureService = DependencyResolver.Current.GetService();
}
///
///
///
///
public void ProcessRequest(HttpContext context)
{
//文件保存目录路径
//文件保存目录URL
//定义允许上传的文件扩展名
var extTable = new Hashtable
{
{"image", "gif,jpg,jpeg,png,bmp"},
{"flash", "swf,flv"},
{"media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"},
{"file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"}
};
//最大文件大小
const int maxSize = 1000000;
this.context = context;
HttpPostedFile imgFile = context.Request.Files["imgFile"];
if (imgFile == null)
{
ShowError("请选择文件。");
}
string dirName = context.Request.QueryString["dir"];
if (string.IsNullOrEmpty(dirName))
{
dirName = "image";
}
if (!extTable.ContainsKey(dirName))
{
ShowError("目录名不正确。");
}
string fileName = imgFile.FileName;
string fileExt = Path.GetExtension(fileName).ToLower();
if (imgFile.InputStream.Length > maxSize)
{
ShowError("上传文件大小超过限制。");
}
if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(((string)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
{
ShowError("上传文件扩展名是不允许的扩展名。\n只允许" + ((string)extTable[dirName]) + "格式。");
}
string result = string.Empty;
string filePath = "";
using (Stream newStream = imgFile.InputStream.Copy())
{
using (Image image = Image.FromStream(newStream))
{
filePath = DirHelper.OssFilePath(image.Width, image.Height, fileExt);
}
}
result = _fileUploadInfrastructureService.UploadImage(filePath.Replace(@"\", "/"), imgFile.InputStream);
if (!string.IsNullOrWhiteSpace(result))
{
result += "@!1200w";
}
var hash = new Hashtable();
hash["error"] = 0;
hash["url"] = result;
context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
context.Response.Write(JsonMapper.ToJson(hash));
context.Response.End();
}
///
///
///
///
private void ShowError(string message)
{
var hash = new Hashtable();
hash["error"] = 1;
hash["message"] = message;
context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
context.Response.Write(JsonMapper.ToJson(hash));
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}