[Asp.net core 2.0]Ueditor 图片上传

摘要

在项目中要用到富文本编辑器,包含上传图片,插入视频等功能。但ueditor只有.net版本,没有支持core。那么上传等接口就需要自己实现了。

一个例子

首先去百度ueditor官网下载简化版的ueditor。并引入到项目中

如图:

页面引用以下几个文件:

<link href="~/ueditor/themes/default/css/umeditor.css" type="text/css" rel="stylesheet" />
<script src="~/ueditor/third-party/jquery.min.js"></script>
<script src="~/ueditor/umeditor.config.js" charset="utf-8"></script>
<script src="~/ueditor/umeditor.js" charset="utf-8"></script>
<script src="~/ueditor/lang/zh-cn/zh-cn.js"></script>

修改ueditor配置文件:

  //为编辑器实例添加一个路径,这个不能被注释
        UMEDITOR_HOME_URL: URL

        //图片上传配置区
        , imageUrl: "../fileupload/UeditorUpload"             //图片上传提交地址
        , imagePath: URL + "net/"                     //图片修正地址,引用了fixedImagePath,如有特殊需求,可自行配置
        , imageFieldName: "upfile"                   //图片数据的key,若此处修改,需要在后台对应文件修改对应参数


        //工具栏上的所有的功能按钮和下拉框,可以在new编辑器的实例时选择自己需要的从新定义
        , toolbar: [
            'source | undo redo | bold italic underline strikethrough | superscript subscript | forecolor backcolor | removeformat |',
            'insertorderedlist insertunorderedlist | selectall cleardoc paragraph | fontfamily fontsize',
            '| justifyleft justifycenter justifyright justifyjustify |',
            'link unlink | image video |',
            'horizontal print preview fullscreen'
        ]

添加接收文件控制器,并提供接口

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace FireFly.Admin.Controllers
{
    public class FileUploadController : Controller
    {
        private IHostingEnvironment hostingEnv;
        public FileUploadController(IHostingEnvironment env)
        {
            hostingEnv = env;
        }
        public async Task<IActionResult> UeditorUpload()
        {
            var files = Request.Form.Files;
            string callback = Request.Query["callback"];
            string editorId = Request.Query["editorid"];
            if (files != null && files.Count > 0)
            {
                var file = files[0];
                string contentPath = hostingEnv.WebRootPath;
                string fileDir = Path.Combine(contentPath, "upload");
                if (!Directory.Exists(fileDir))
                {
                    Directory.CreateDirectory(fileDir);
                }
                string fileExt = Path.GetExtension(file.FileName);
                string newFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + fileExt;
                string filePath = Path.Combine(fileDir, newFileName);
                using (FileStream fs = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(fs);
                }
                var fileInfo = getUploadInfo("../../upload/" + newFileName, file.FileName,
                    Path.GetFileName(filePath), file.Length, fileExt);
                string json = BuildJson(fileInfo);
              
                Response.ContentType = "text/html";
                if (callback != null)
                {
                    await Response.WriteAsync(String.Format("<script>{0}(JSON.parse(\"{1}\"));</script>", callback, json));
                }
                else
                {
                    await Response.WriteAsync(json);
                }
                return View();
            }
            return NoContent();
        }
        private string BuildJson(Hashtable info)
        {
            List<string> fields = new List<string>();
            string[] keys = new string[] { "originalName", "name", "url", "size", "state", "type" };
            for (int i = 0; i < keys.Length; i++)
            {
                fields.Add(String.Format("\"{0}\": \"{1}\"", keys[i], info[keys[i]]));
            }
            return "{" + String.Join(",", fields) + "}";
        }
        /**
       * 获取上传信息
       * @return Hashtable
       */
        private Hashtable getUploadInfo(string URL, string originalName, string name, long size, string type, string state = "SUCCESS")
        {
            Hashtable infoList = new Hashtable();

            infoList.Add("state", state);
            infoList.Add("url", URL);
            infoList.Add("originalName", originalName);
            infoList.Add("name", Path.GetFileName(URL));
            infoList.Add("size", size);
            infoList.Add("type", Path.GetExtension(originalName));

            return infoList;
        }
    }

}

测试

总结

这里简单实现了ueditor在asp.net core 2.0 web应用中的使用,需要实现的只是文件的上传接口。

posted @ 2018-01-19 15:11  wolfy  阅读(2514)  评论(3编辑  收藏  举报