【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="30" cols="80" style="width: 96%">@Model</textarea>
<script type="text/javascript">
    $(document).ready(function () {
        $('#@ViewData.ModelMetadata.PropertyName').xheditor({ upMultiple: 5, 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"];     //配置文件: 上传文件保存路径,结尾不要带/
            string imagesDomain = WebConfigurationManager.AppSettings["ImagesDomain"];         //配置文件:网站域名
            int dirtype = 1;                 // 1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存
            int maxattachsize = 2097152;     // 最大上传大小,默认是2M
            string upext = "txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid";    // 上传扩展名
            int msgtype = 2;                 //返回上传参数的格式: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[1].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, 0, fileData.ContentLength);
                stream.Close();

                //filecollection = null;
            }

            if (file.Length == 0) err = "无数据提交";
            else
            {
                if (file.Length > maxattachsize) err = "文件大小超过" + maxattachsize + "字节";
                else
                {
                    string attach_dir, attach_subdir, filename, extension, target;

                    // 取上载文件后缀名
                    extension = GetFileExt(localname);

                    if (("," + upext + ",").IndexOf("," + extension + ",") < 0) err = "上传文件扩展名必需为:" + upext;
                    else
                    {
                        switch (dirtype)
                        {
                            case 2:
                                attach_subdir = "month_" + DateTime.Now.ToString("yyMM");
                                break;
                            case 3:
                                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(10000) + "." + 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, 0, file.Length);
                            fs.Flush();
                            fs.Close();
                        }
                        catch (Exception ex)
                        {
                            err = ex.Message.ToString();
                        }

                        // 立即模式判断
                        if (immediate == "1") target = "!" + target;
                        target = jsonString(target);
                        if (msgtype == 1)
                        {
                            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('.') + 1).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="12" cols="80" 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.2/xheditor-1.2.2.min.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/Scripts/xheditor-1.2.2/xheditor_lang/zh-cn.js")"></script>
    <script type="text/javascript">
        $('#elm2').xheditor({ upImgUrl: "@Url.Action("XhUpload","Image")", upImgExt: "jpg,jpeg,gif,png" });
    </script>
}

效果图:

 

 

时间: 2024-08-03 18:08:13

【HTML5+MVC4】xhEditor网页编辑器图片上传的相关文章

kindediorz在线编辑器图片上传

问题描述 kindediorz在线编辑器图片上传 在编辑器中选中图片之后,执行上传,页面提示找不到上传路径,我看了一下是默认的路径,怎么会找不到呢,求 web大神帮助小弟解决这个问题 解决方案 换个UUpoop试试,这个也可以实现在线编辑图片上传功能 http://www.uupoop.com/zp/

javascript-kindeditor文本编辑器图片上传成功,但是报js错误

问题描述 kindeditor文本编辑器图片上传成功,但是报js错误 图片上传功能没有任何问题,但是会报这个js错误.这个问题,在chrome浏览器没有问题,在IE就会出现.有什么办法可以解决这个问题呢. 解决方案 你这个提示框是chrome的吧..IE的没见过这种提示框,除非自己用层模拟的.自己看1448行是什么代码 而且你jquery主版本大于2,不再支持ie8-浏览器,要支持ie8-换小于2的jquery

gbk转utf-8 百度编辑器图片上传描述信息

问题描述 gbk转utf-8 百度编辑器图片上传描述信息 5C while((n=in.read(c))!=-1){ String gbk=new String(new String(c0n).getBytes(""GBK"")UTF-8""); String iso = new String(gbk.getBytes(""UTF-8"")ISO-8859-1""); System.ou

simditor文本编辑器图片上传,不要网上那种strust的

问题描述 simditor文本编辑器图片上传,不要网上那种strust的 simditor文本编辑器图片上传,不要网上那种strust的 我就好奇了simditor也不是那种很没名气的富文本啊 为什么晚上教程少的要死然后全是一模一样的,希望哪位大神给个图片上传的教程或源码,Hibernate+spring+maven的 不要strust的 就算改那个代码都上传不了我已经试过了 解决方案 http://www.jq22.com/jquery-info590/

百度UEditor编辑器图片上传目录的修改设置教程

方法一,通过修改php来改变UEditor编辑器图片上传目录 UEditor的图片上传需要自己设置一下功能才能正常.同时,如下图所示,图片上传插件的"在线管理"."图片搜索"等无意义的功能,需要自己手动根除一下.   还有,一般情况下,编辑器的图片存储目录,上传目录就是一个,不应该给用户自己手动选择,也是需要自己手动删除的. 修改过程如下: 1.首先打开(ueditor1_3_6-utf8-php根目录)\php\config.php将代码改成如下所示:    &l

通过Fckeditor把图片上传到独立图片服务器的方法_网页编辑器

我大概思考了下有如下几种方法可以解决: 1.在图片服务器上开通FTP,人为添加图片地址即可,但不方便,特别是在可视编辑器中看图还的多一部操作. 2.在图片服务器上开通FTP,并提高IIS执行dosShell访问ftp,但是不安全. 3.在图片服务器上开通IIS,WEB后台直接访问(还是存在在编辑器中不方便查看的问题,但可以用js控制上传后自动追加到HTML编辑窗口中) 4.利用现有在线编辑器的上传程序来实现. 第三,四种方法比较靠谱,但还需要解决跨域问题,第三种还要单独写程序,改动比较大,用第四

FCKeditor 图片上传进度条不动的解决方法_网页编辑器

因为昨天晚上急着要把理事会员的图片送上网,所以采用FTP传送图片,然后使用<img src="/Upload/abcd.jpg" />这样的笨方法把图片全部搞定. 今天上午8点,开始研究这个问题,在网上查到了这样的帖子,原文如下: 最近有个项目用到FCKEditor,载了目前最新版的2.6.4,配置一切OK,调试状态一切OK,发布到服务器(windows server 2003 sp2),问题来了-- 上传图片后页面左下脚出现脚本错误提示,点开可看到是"没有权限&

扩展FCKeditor编辑器的图片上传功能

在我使用的个人博客(Mr.d's Time)中,后台的文章发布使用的是FCKeditor编辑器,在FCKeditor编辑器中通过简单的配置就能使用已提 供的图片上传的功能.但没有提供对上传后的图片进行管理,从而无法满足我日后的各种应用场景,比如:使用已上传的文件.删除已上传的 文件等等,以至于在写博时,遇到"在文章中要插入图片"这样的应用让我的操作很繁琐(上传图片---记住文件件 ---手工写Url),因此无 法让我享受到在写博时的快感.从而让我有了扩展FCKeditor编辑器图片上传

html5在小米手机上图片上传无法获取文件名

问题描述 html5在小米手机上图片上传无法获取文件名 <input type=""file"" id=""file1"" name=""file1"" onchange=""preImage(1this.files);""accept=""image/*"">function preImage(