|
nodejs中有很多的富文本插件。但是这些富文本插件都是基于中间件,如果要在egg.js配置nodejs富文本插件的话比较麻烦。
下面给大家推荐一筐egg.js富文本插件wysiwyg-editor的使用。
效果图:
使用方法:
1、wysiwyg-editor基于jquery所以要引入jquery,其次引入下面的js以及css
- <!-- Include CSS for icons. -->
- <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
- <!-- Include Editor style. -->
- <link href="https://cdnjs.cloudflare.com/ajax/libs/froala-editor/2.5.1/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />
- <link href="https://cdnjs.cloudflare.com/ajax/libs/froala-editor/2.5.1/css/froala_style.min.css" rel="stylesheet" type="text/css" />
- <!-- Include jQuery lib. -->
- <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
- <!-- Include Editor JS files. -->
- <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/froala-editor/2.5.1//js/froala_editor.pkgd.min.js"></script>
- <!-- Initialize the editor. -->
复制代码
2、页面中定义一个textarea
- <textarea name="content" id="content"></textarea>
复制代码
3、配置egg.js富文本插件wysiwyg-editor
- <script>
- $(function() {
- $('#content').froalaEditor({
- height: 300,
- imageUploadURL: '/admin/goods/uploadImg'
- })
- });
- </script>
复制代码
官方文档:https://www.froala.com/wysiwyg-editor/docs/options#imageUploadURL
egg.js后台接受上传的图片:
注意后台返回数据的格式:
{link: 图片地址}
- async uploadImg() {
- let parts = this.ctx.multipart({ autoFields: true });
- let files = {};
- let stream;
- while ((stream = await parts()) != null) {
- if (!stream.filename) {
- break;
- }
- let fieldname = stream.fieldname; //file表单的名字
- //上传图片的目录
- let dir=await this.service.tools.getUploadFile(stream.filename);
- let target = dir.uploadDir;
- let writeStream = fs.createWriteStream(target);
- await pump(stream, writeStream);
- files=Object.assign(files,{
- [fieldname]:dir.saveDir
- })
-
- }
-
- console.log(files,parts.field);
- this.ctx.body={link: files.file};
- }
-
复制代码
最后还要配置csrf。
- exports.security = {
- csrf: {
- // 判断是否需要 ignore 的方法,请求上下文 context 作为第一个参数
- ignore: ctx => {
- if(ctx.request.url=='/admin/goods/uploadImg'){
- return true;
- }
- return false;
-
- },
- },
- }
复制代码
|
|