项目使用django写的,要在前端结合完成富文本上传图片的功能,代码,如下:
首先建立js文件,config.js 里面写kindeditor的配置
// 实例化编辑器
$(function(){
var title = $('#lan').text();
KindEditor.ready(function(K) {
K.create('#editor_id', {
//create 括号中的内容为获取textarea的这个文本域 你可以使用CSS选择器获取
// 如:create(#xxx) #xxx 对应 textarea id= 'xxx' ,这个id在当前页面只能存在1个
// 或create(textarea) 条件是当前页面当中只存在1个 textarea
//花括号存放富文本配置信息 如 width:600px
// width:'660px;',
// height:'300px;',
uploadJson:'/warn/image/', //处理图片路由
items:[
'undo', 'redo', '|', 'preview', 'template', 'cut', 'copy', 'paste',
'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
'superscript', 'quickformat', 'selectall', '/',
'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage',
'table', 'hr', 'emoticons', 'pagebreak', 'link', 'unlink', '|', 'about'
], //定制操作
resizeType:0,
themeType:'simple',
langType:title //控制语言
});
});
})
import os
import time
import uuid #随机字符串
@csrf_exempt
def imageview(request):
if request.method == 'POST':
item = {}
file = request.FILES.get('imgFile')
ext_name = file.name.rfind('.')
localtime = time.strftime('%Y/%m/%d', time.localtime())
path = createfiles(localtime) + '/'
print(path)
file_name = str(uuid.uuid1()) + file.name[ext_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)
def createfiles(path):
file_dirs = os.path.join(settings.BASE_DIR,'media','test',path)
path = os.path.join('media/test/',path)
if not os.path.exists(path):
os.makedirs(file_dirs)
return path
页面直接引入js 文件就好了