using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;

/// <summary>
/// UploadHandler 的摘要说明
/// </summary>
public class UploadHandler : Handler
{

public UploadConfig UploadConfig { get; private set; }
public UploadResult Result { get; private set; }

public UploadHandler(HttpContext context, UploadConfig config)
: base(context)
{
this.UploadConfig = config;
this.Result = new UploadResult() { State = UploadState.Unknown };
}

public override void Process()
{
byte[] uploadFileBytes = null;
string uploadFileName = null;

if (UploadConfig.Base64)
{
uploadFileName = UploadConfig.Base64Filename;
uploadFileBytes = Convert.FromBase64String(Request[UploadConfig.UploadFieldName]);
}
else
{
var file = Request.Files[UploadConfig.UploadFieldName];
uploadFileName = file.FileName;

if (!CheckFileType(uploadFileName))
{
Result.State = UploadState.TypeNotAllow;
WriteResult();
return;
}
if (!CheckFileSize(file.ContentLength))
{
Result.State = UploadState.SizeLimitExceed;
WriteResult();
return;
}

uploadFileBytes = new byte[file.ContentLength];
try
{
file.InputStream.Read(uploadFileBytes, 0, file.ContentLength);
}
catch (Exception)
{
Result.State = UploadState.NetworkError;
WriteResult();
}
}

Result.OriginFileName = uploadFileName;

var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat);
//UploadConfig.PathFormat=D:/UploadFiles/Hospital/{yyyy}{mm}{dd}/{time}{rand:6}
//savePath =D:/UploadFiles/Hospital/20151027/6358155709153650499167466.png
var localPath = savePath;// Server.MapPath(savePath);
try
{
#region UEditor本身
//if (!Directory.Exists(Path.GetDirectoryName(localPath)))
//{
// Directory.CreateDirectory(Path.GetDirectoryName(localPath));
//}
//File.WriteAllBytes(localPath, uploadFileBytes);

//////压缩图片大小
////System.Drawing.Image originalImage = System.Drawing.Image.FromFile(localPath);
////int w = originalImage.Width;
////int h = originalImage.Height;
////originalImage.Dispose();
////返回路径
//Result.Url = savePath.Substring(UploadConfig.PathFormat.IndexOf('{'));// savePath;
//Result.State = UploadState.Success;
#endregion

#region 调用接口上传图片修改
//调用接口上传图片
string picUrl = string.Empty;

FormItemModel formInfo = new FormItemModel() //提交文件参数
{
Key = "file",
Value = string.Empty,
FileName = uploadFileName,
FileContent = new MemoryStream(uploadFileBytes)
};

ResponseMessageInfo responseInfo = Common.HttpPostFuns.Instance().PostFile(Common.CommonConst.PlatUploadFileUrl, Common.CommonConst.OperationBackProjectCode, formInfo);

if (responseInfo.code != "200")
{
throw new Common.BizTipsException(responseInfo.code, responseInfo.message);
}

System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var jArr = Newtonsoft.Json.Linq.JArray.Parse(jss.Serialize(responseInfo.responseData));
if (jArr.Count > 0)
{
Newtonsoft.Json.Linq.JObject jo = (Newtonsoft.Json.Linq.JObject)jArr[0];
picUrl = jo["url"].ToString();
}
//Result.Url = picUrl.Substring(UploadConfig.PathFormat.IndexOf('{'));// savePath;
Result.Url = picUrl;
Result.State = UploadState.Success;
#endregion

}
catch (Exception e)
{
Result.State = UploadState.FileAccessError;
Result.ErrorMessage = e.Message;
}
finally
{
WriteResult();
}
}

private void WriteResult()
{
this.WriteJson(new
{
state = GetStateMessage(Result.State),
url = Result.Url,
title = Result.OriginFileName,
original = Result.OriginFileName,
error = Result.ErrorMessage
});
}

private string GetStateMessage(UploadState state)
{
switch (state)
{
case UploadState.Success:
return "SUCCESS";
case UploadState.FileAccessError:
return "文件访问出错,请检查写入权限";
case UploadState.SizeLimitExceed:
return "文件大小超出服务器限制";
case UploadState.TypeNotAllow:
return "不允许的文件格式";
case UploadState.NetworkError:
return "网络错误";
}
return "未知错误";
}

private bool CheckFileType(string filename)
{
var fileExtension = Path.GetExtension(filename).ToLower();
return UploadConfig.AllowExtensions.Select(x => x.ToLower()).Contains(fileExtension);
}

private bool CheckFileSize(int size)
{
return size < UploadConfig.SizeLimit;
}
}

public class UploadConfig
{
/// <summary>
/// 文件命名规则
/// </summary>
public string PathFormat { get; set; }

/// <summary>
/// 上传表单域名称
/// </summary>
public string UploadFieldName { get; set; }

/// <summary>
/// 上传大小限制
/// </summary>
public int SizeLimit { get; set; }

/// <summary>
/// 上传允许的文件格式
/// </summary>
public string[] AllowExtensions { get; set; }

/// <summary>
/// 文件是否以 Base64 的形式上传
/// </summary>
public bool Base64 { get; set; }

/// <summary>
/// Base64 字符串所表示的文件名
/// </summary>
public string Base64Filename { get; set; }
}

public class UploadResult
{
public UploadState State { get; set; }
public string Url { get; set; }
public string OriginFileName { get; set; }

public string ErrorMessage { get; set; }
}

public enum UploadState
{
Success = 0,
SizeLimitExceed = -1,
TypeNotAllow = -2,
FileAccessError = -3,
NetworkError = -4,
Unknown = 1,
}

UEditor上传文件的默认地址修改的更多相关文章

  1. Asp.net 上传文件小叙(修改FileUpload显示文字等)

    想要在asp.net网站上上传文件就得用到FileUpload,可是这个控件中“浏览”没法修改,可以使用html中<input type="file" 来解决该问题. 首先页 ...

  2. FastDFS上传文件访问url地址直接下载

    fdfs 存储节点storage安装nginx,修改nginx配置文件 location ~/group[1-9]/M00 {  if ( $query_string ~* ^(.*)paramete ...

  3. js上传文件获取客户端地址

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  4. evpp 上传文件问题转

    背景 因为项目需求,需要使用360的evpp库,来实现一个接口,支持文件上传. 实际操作过程中,发现了一些问题,记录下来. 前端文件上传方式 简单的使用input标签 <body> < ...

  5. Ajax方式上传文件

    用到两个对象 第一个对象:FormData 第二个对象:XMLHttpRequest 目前新版的Firefox 与 Chrome 等支持HTML5的浏览器完美的支持这两个对象,但IE9尚未支持 For ...

  6. 纯js上传文件 很好用

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name ...

  7. 使用XWAF框架(2)——上传文件

    XWAF提供了上传文件的HttpFileUploader工具类,具备强大的多文件上传.文件类型过滤.文件大小限制.存储目录设置.文件名称更改等功能,简化了Web应用开发的编程工作. 它能同时解析表单参 ...

  8. 上传文件,经过Zuul,中文文件名乱码解决办法

    转载请标明出处: http://blog.csdn.net/forezp/article/details/77170470 本文出自方志朋的博客 问题描述 在项目中又一个上传文件的oss服务,直接调用 ...

  9. 向vsftp服务器上传文件报“550 Permission denied”错误的解决办法

    上传文件: ftp> mput db.iso 550 Permission denied 原因:vsftp默认配置不允许上传文件. 解决:修改/etc/vsftpd.conf 将“write_e ...

随机推荐

  1. Drools的HelloWord例子

    添加drools框架运行的依赖 <!--Drools 规则相关 --> <dependency> <groupId>org.drools</groupId&g ...

  2. Vue 内容分发slot

    1.概述 内容分发:混合父组件的内容与子组件自己的模板. 2.单个插槽 当子组件模板只有一个没有属性的插槽时,父组件传入的整个内容片段将插入到插槽所在的 DOM 位置,并替换掉插槽标签本身. 最初在  ...

  3. Shell脚本之:数组

    bash支持一维数组,并且没有限定数组的大小,数组元素的下标由0开始编号. 定义数组 在Shell中,用括号来表示数组,数组元素用“空格”符号分割开.定义数组的一般形式为: array_name=(v ...

  4. css样式控制元素固定在底部

    回复固定在底部:css样式用到了 box-sizing属性 box-sizing:border-box; -moz-box-sizing:border-box; /* Firefox */ -webk ...

  5. C#获取webbrowser完整cookie

    [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)] //API设定Cookie stat ...

  6. syslog,rsyslog and syslog-ng

    http://en.wikipedia.org/wiki/Syslog Syslog is a standard for computer message logging. It permits se ...

  7. LeetCode 之 Valid Palindrome(字符串)

    [问题描写叙述] Given a string, determine if it is a palindrome, considering only alphanumeric characters a ...

  8. mysql忘记root密码且忘了安装目录如何修改root密码

    问题背景 很久之前在本机上安装mysql,也没用过(主要是用Oracle),导致root密码忘记.更严重的是,连自己的安装目录都忘记了. 遇到的问题 1.在任务管理器可以找到mysql的服务已经起来, ...

  9. 我眼中的Oracle Database Software 和 Oracle Database

    我眼中的Oracle Database Software 和 Oracle Database 我喜欢用微软的office软件和word文档(确切的说是:自己写的word文档,能够把这个Word文档想象 ...

  10. linux memcached php 整合

    http://blog.csdn.net/liruxing1715/article/details/8269563