打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Django使用summernote富文本编辑器,完整前后端

今天项目中要使用summernote富文本编辑器,由于网上的基本都是在说用这个编辑器上传图片的,所以我就整理了一下上传图片和文本的代码,完整前后端。

这里我准备了一个demo,需要的可以直接复制

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Summernote</title>    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>    <link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.11/summernote.css" rel="stylesheet">    <script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.11/summernote.js"></script></head><body><div style="width: 60%;margin:20px auto" >    <div id="summernote"></div></div><script>    $(document).ready(function() {        $('#summernote').summernote({            height : '200px',            placeholder: 'Hello hello hello ...',            lang : 'zh-CN',            callbacks: {                onImageUpload: function(files, editor, $editable) {                    sendFile(files);                }            },            toolbar: [                          [ 'style', [ 'style' ] ],                          [ 'font', [ 'bold', 'italic',  'clear'] ],                          [ 'fontname', [ 'fontname' ] ],                          [ 'fontsize', [ 'fontsize' ] ],                          [ 'color', [ 'color' ] ],                          [ 'para', [ 'ol', 'ul', 'paragraph', 'height' ] ],                          ['picture'],                          [ 'table', [ 'table' ] ],                          [ 'insert', [ 'link'] ],                          [ 'view', [ 'undo', 'redo', 'fullscreen', 'codeview', 'help' ] ]				          ]        });    });</script></body></html>

这是富文本编辑器的效果图


下面附上js代码,包括提交图片和文本

<form id="ftn">      {% csrf_token %}      <div>      		<input type="text" id="title" name="title" placeholder="请输入帖子标题"/>      		<div>                  <input class="summernote" id="summernote" name="content">            </div>       </div>       <button type="button" onclick="save()">提交</button> </form><script>    /**     * 编辑器新增的ajax上传图片函数     * @param files     * @param editor     * @param $editable     * @returns {boolean}     */    function sendFile(files, editor, $editable) {        var size = files[0].size;        if((size / 1024 / 1024) > 2) {            alert("图片大小不能超过2M...");            return false;        }        var formData = new FormData();        formData.append("file", files[0]);        $.ajax({            data : formData,            type : "POST",            url : "/instantuploa/",    // 图片上传出来的url,返回的是图片上传后的路径,http格式            cache : false,            contentType : false,            processData : false,            dataType : "json",            success: function(response) {//data是返回的hash,key之类的值,key是定义的文件名                if (response['status'] == 1){                    //将图片插入到编辑框内                    $('#summernote').summernote('insertImage', response.file, 'img');                }else{                    alert('上传失败,请重新上传!');                    return false                }            },            error:function(){                alert("上传失败");            }        });    }    function save() {        var tet = $('#summernote').summernote('code' );        var title = $('#title').val();        var data = {            content : tet,            title : title,        };        console.log(data);        $.ajax({            cache: true,            type: 'POST',            url:'/text/',            data:data,            success:function (data) {				//写上你的回调处理            }        })    }</script>

接下里是Django后端的接收代码

from django.shortcuts import render,redirect,HttpResponsefrom django.contrib.auth.decorators import login_requiredfrom django.views.decorators.csrf import csrf_exemp@login_required@csrf_exemptdef text(request):    # 获取富文本编辑器中的数据    if request.method == "POST":        title = request.POST.get('title')        print(title)        content = request.POST.get('content')        print(content)    return render(request,'index.html')# 上传图片@login_required@csrf_exemptdef instantuploa(request):    if request.method == 'POST':        # 拿到图片对象        content_img = request.FILES['file']        # 判断图片大小        if content_img.size/1024/1024 < 2:            # 判断图片格式是否为规定的格式            if content_img.content_type == 'image/jpeg' or content_img.content_type == 'image/jpg' or content_img.content_type == 'image/png':                # 获取当前结构化时间用于拼接图片名称                nowtime = datetime.datetime.now().strftime('%Y%m%d%H%S')                # 创建一个文件                path = os.path.join(settings.MEDIA_ROOT,nowtime   content_img.name)                # 写文件 遍历图片文件流                with open(path, 'wb') as f:                    for content in content_img.chunks():                        f.write(content)                # 关闭文件流                f.close()                # 拼接文件名和路径                user_img = '图片存放的路径{}'.format(nowtime   content_img.name)                # 返回图片路径                response = {                    "status": 1,                    "message": "上传成功",                    'file': user_img,                }                return HttpResponse(json.dumps(response))            else:                response={                    "status": 0,                    "message": "只能上传jpeg、jpg、png格式的图片!",                }                return HttpResponse(json.dumps(response))        else:            response = {                "status": 0,                "message": "图片超过了2M!",            }            return HttpResponse(json.dumps(response))

图片上传的具体设置步骤请参考:https://blog.csdn.net/weixin_45457042/article/details/103975741
希望对您有所帮助。有疑问可以留言。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
基于jquery的bootstrap在线文本编辑器插件Summernote
网站实用技巧(上)
HTML在线编辑器的调用方法和使用方法详解 - 遇见未来
14款web前端常用的富文本编辑器插件
add()
关于XSS(跨站脚本攻击)和CSRF(跨站请求伪造)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服