使用kindeditor上传

富文本编辑框的使用,包含用户的上传图片和回显

1.从官网上下载kindeditor(http://kindeditor.net/doc.php)

<script src="/static/js/kindeditor-all-min.js"></script>
<script src="/static/js/zh-CN.js"></script>

2.html中写一个textarea文本框

 <textarea class="form-control" id="editor_id"></textarea>

3.初始化kindeditor

<script type="text/javascript">
    var editor;
    KindEditor.ready(function(K) {
        //详细配置可以参考官方文档
      editor = K.create('#editor_id', { //这里的id 为textarea的ID
      width : '100%',
      height:"300px",
      allowImageUpload : true,
      uploadJson:"http://127.0.0.1:8005/news_file_upload.html/",
      extraFileUploadParams:{
            csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']")
      } ,
          //上传类型,分别为image、flash、media、file
        {#dir : "image",#}
      items : [
      'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 			'cut', 'copy', 'paste',
        'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
        'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 		'subscript',
        'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
        'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
        'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 			'image', 'multiimage',
        'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 			'pagebreak',
        'anchor', 'link', 'unlink', '|', 'about']
      });
    });
    </script>

4.django后台代码

settings.py里配置
	MEDIA_ROOT = os.path.join(BASE_DIR, "news_file") # 我这里默认上传到news_file目录下
urls.py里配置
	from django.views.static import serve
	from django.conf import settings
	url(r'^news_file/(?P<path>.*)$', serve, {"document_root": settings.MEDIA_ROOT}),

######  4.1获取文件路径
def createfiles(path):
    file_dirs = os.path.join(settings.BASE_DIR,'news_file','imgs',path)
    path = os.path.join('news_file/imgs/',path)
    if not os.path.exists(path):
        os.makedirs(file_dirs)
    return path
4.2 文件上传
def news_upload(request):
    if request.method == 'POST':
        item = {}
        file = request.FILES.get('imgFile')
        print(file.name)
        ext_name = file.name.rfind('.')
        print(ext_name)
        localtime = time.strftime('%Y/%m/%d', time.localtime())

        path = createfiles(localtime) + '/'
        print(path)
        file_name = str(uuid.uuid1()) + file.name
        file_path = os.path.join(path, file_name)
        print(file_path)

        with open(file_path, 'wb') as f:
            for temp in file.chunks():
                f.write(temp)
        item['message'] = '上传成功'
        item['url'] = '/' + file_path
        item['error'] = 0

        print(item['url'])
        return JsonResponse(item)

posted @ 2018-11-28 22:51  小猫妮  阅读(273)  评论(0编辑  收藏  举报