【HTML5+MVC4】xhEditor网页编辑器图片上传

准备工作:

创建一个MVC项目中,添加好xhEditor插件

相关用法:http://www.cnblogs.com/xcsn/p/4701497.html

注意事项:xhEditor分为v1.1.14和v1.2.2两个版本

如果用v1.1.14,jq版本<1.8,如果使用,请下载http://jquery.com/download/的 jQuery Migrate Plugin,即可支持

1.定义模板RichText.cshtml

文件路径:Views/Shared/EditorTemplates/

<textarea id="@ViewData.ModelMetadata.PropertyName" name="@ViewData.ModelMetadata.PropertyName" rows="" cols="" style="width: 96%">@Model</textarea>
<script type="text/javascript">
$(document).ready(function () {
$('#@ViewData.ModelMetadata.PropertyName').xheditor({ upMultiple: , upImgUrl: '@Url.Content("~/Images/XhUpload")',upImgExt: 'jpg,jpeg,gif,png' });
});
</script>

2.编辑器图片上传的控制器方法,注意要修改配置文件信息,包含图片上传路径和域名

#region XhEditor网页编辑器图片上传【HTML5+】
/// <summary>
/// XhEditor网页编辑器图片上传【HTML5+】
/// </summary>
/// <param name="fileData"></param>
/// <returns></returns>
[HttpPost]
public ActionResult XhUpload(HttpPostedFileBase fileData)
{
Response.Charset = "UTF-8"; // 初始化一大堆变量
//string inputname = "filedata";//表单文件域name
string xheditorUpload = WebConfigurationManager.AppSettings["XheditorUpload"]; //配置文件: 上传文件保存路径,结尾不要带/

         var url = Request.Url.ToString();
         string imagesDomain = url.Substring(0,url.NthIndexOf('/',3));

            //string imagesDomain = WebConfigurationManager.AppSettings["ImagesDomain"];         //配置文件:网站域名

            int dirtype = ;                 // 1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存
int maxattachsize = ; // 最大上传大小,默认是2M
string upext = "txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid"; // 上传扩展名
int msgtype = ; //返回上传参数的格式:1,只返回url,2,返回参数数组
string immediate = Request.QueryString["immediate"];//立即上传模式,仅为演示用
byte[] file; // 统一转换为byte数组处理
string localname = "";
string disposition = Request.ServerVariables["HTTP_CONTENT_DISPOSITION"]; string err = "";
string msg = "''"; if (disposition != null)
{
// HTML5上传
file = Request.BinaryRead(Request.TotalBytes);
localname = Server.UrlDecode(Regex.Match(disposition, "filename=\"(.+?)\"").Groups[].Value);// 读取原始文件名
}
else
{
//HttpFileCollectionBase filecollection = Request.Files;
//HttpPostedFileBase fileData = filecollection.Get(inputname); // 读取原始文件名
localname = fileData.FileName;
// 初始化byte长度.
file = new Byte[fileData.ContentLength]; // 转换为byte类型
System.IO.Stream stream = fileData.InputStream;
stream.Read(file, , fileData.ContentLength);
stream.Close(); //filecollection = null;
} if (file.Length == ) err = "无数据提交";
else
{
if (file.Length > maxattachsize) err = "文件大小超过" + maxattachsize + "字节";
else
{
string attach_dir, attach_subdir, filename, extension, target; // 取上载文件后缀名
extension = GetFileExt(localname); if (("," + upext + ",").IndexOf("," + extension + ",") < ) err = "上传文件扩展名必需为:" + upext;
else
{
switch (dirtype)
{
case :
attach_subdir = "month_" + DateTime.Now.ToString("yyMM");
break;
case :
attach_subdir = "ext_" + extension;
break;
default:
attach_subdir = "day_" + DateTime.Now.ToString("yyMMdd");
break;
}
attach_dir = xheditorUpload.Replace("~/", "") + "/" + attach_subdir + "/"; // 生成随机文件名
Random random = new Random(DateTime.Now.Millisecond);
filename = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next() + "." + extension; target = attach_dir + filename;
try
{
CreateFolder(Server.MapPath("~/" + attach_dir)); System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("~/" + target), System.IO.FileMode.Create, System.IO.FileAccess.Write);
fs.Write(file, , file.Length);
fs.Flush();
fs.Close();
}
catch (Exception ex)
{
err = ex.Message.ToString();
} // 立即模式判断
if (immediate == "") target = "!" + target;
target = jsonString(target);
if (msgtype == )
{
msg = "'" + imagesDomain + "/" + target + "'";
}
else
{
//url必须为绝对路径
msg = "{'url':'" + imagesDomain + "/" + target + "','localname':'" + jsonString(localname) + "','id':'1'}";
}
}
}
} file = null; //Response.Write("{'err':'" + jsonString(err) + "','msg':" + msg + "}");
return this.Content("{'err':'" + jsonString(err) + "','msg':" + msg + "}");
} string jsonString(string str)
{
str = str.Replace("\\", "\\\\");
str = str.Replace("/", "\\/");
str = str.Replace("'", "\\'");
return str;
} string GetFileExt(string FullPath)
{
if (FullPath != "") return FullPath.Substring(FullPath.LastIndexOf('.') + ).ToLower();
else return "";
} void CreateFolder(string FolderPath)
{
if (!System.IO.Directory.Exists(FolderPath)) System.IO.Directory.CreateDirectory(FolderPath);
}
#endregion

3.设置Model字段类型

        [DataType("RichText")]
public string Texts { get; set; }

4.页面添加

@Html.EditorFor(t => t.Texts)

如果你只是为了测试下,使用以下测试页面,再加上 第二步即可。

以下相关代码请根据自己的情况修改

@{
ViewBag.Title = "Home Page";
} <div class="row">
<form id="InputFrm" name="InputFrm" action="@Url.Action("Save")" method="post" class="form-group">
<div class="form-group">
<textarea id="elm2" name="elm2" class="xheditor-mfull" rows="" cols="" style="width: 80%"></textarea>
</div>
<input type="submit" name="save" value="Submit" /> </form>
</div>
@section scripts
{
<script type="text/javascript" src="@Url.Content("~/Scripts/xheditor-1.2./xheditor-1.2..min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/xheditor-1.2./xheditor_lang/zh-cn.js")"></script>
<script type="text/javascript">
$('#elm2').xheditor({ upImgUrl: "@Url.Action("XhUpload","Image")", upImgExt: "jpg,jpeg,gif,png" });
</script>
}

效果图:

【HTML5+MVC4】xhEditor网页编辑器图片上传

上一篇:Android——播放器和图片轮播


下一篇:Android学习笔记之图片轮播...