【Django组件】KindEditor富文本编辑器上传文件,html样式文本,VUE异步提交数据(易懂版)

1:下载与配置

适合版本: python3

下载:http://kindeditor.net/down.php

文档:http://kindeditor.net/doc.php

将文件包放入static文件夹内并且配置:

settings.py配置:

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
    os.path.join(BASE_DIR, "media"),
]

# Django用户上传的都叫media文件
MEDIA_URL = "/media/"
# media配置,用户上传的文件都默认放在这个文件夹下
MEDIA_ROOT = os.path.join(BASE_DIR, "media")


REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [],
    "DEFAULT_PERMISSION_CLASSES": [],
}

 

2:前端代码:

html部分:

<div id="app">

    <div>
        <p>内容(TinyMCE编辑器,支持拖放/粘贴上传图片) </p>
        <textarea name="article_content" id="article_content" cols="60" rows="20"
                  style="width: 100%" v-model="article_contents">
        </textarea>
    </div>
    <input type="submit" class="btn btn-info" @click="submits">

</div>


JS部分:
<script src="/static/js/jquery-3.4.1.min.js"></script>
<script src="/static/js/popper.js"></script>
<script src="/static/js/bootstrap.js"></script>
<script charset="utf-8" src="/static/kindeditor/kindeditor-all-min.js"></script>
// 配置属性 <script> KindEditor.ready(function (K) { window.editor = K.create('#article_content', { width: "100%", height: "500px", allowFileManager: true, afterCreate: function () { this.sync(); }, afterBlur: function () { this.sync(); }, uploadJson: "/KindEditor/up/", // 请求路由

filePostName: "upload_img" // 后端获取的参数名字
}); }); </script>
// 配置属性
<script type="text/javascript" src="/static/js/vue.min.js"></script> 
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
var vm = new Vue({
el: '#app',
data: {
article_contents: "",
},
methods: {
submits() {
console.log("KindEditor", KindEditor.instances[0].html()) // 获取到图片的/样式以及内容
},

}
})
</script>

3:上传文件,图片之类的,配置后端路由

1:上传文件路由配置:
    # 上传图片,文件
    url('KindEditor/up/', upImage.upload),




2:upImage.py:

# 上传图片
from django.http import HttpResponse
from car import settings
import os, json
from django.shortcuts import render, HttpResponse, redirect


def upload(request):
    # 上传服务器图片
    image_fils = request.FILES.get("upload_img")
    path = os.path.join(settings.MEDIA_ROOT, "userimg", image_fils.name)  # 路径

    # 创建文件夹目录
    file_path = os.path.join(settings.MEDIA_ROOT, "userimg")
    if not os.path.exists(file_path):
        os.makedirs(file_path)

    # 写到服务器
    with open(path, "wb") as f:
        for line in image_fils.chunks():
            f.write(line)
            f.close()

    # 返回图片给前端
    res = {
        "error": 0,
        "url": "/static/userimg/" + image_fils.name
    }

    return HttpResponse(json.dumps(res))

 

posted @ 2020-05-17 15:53  PythonNew_Mr.Wang  Views(486)  Comments(0Edit  收藏  举报