summernote富文本编辑器,由于网上的基本都是在说用这个编辑器上传图片的,所以我就整理了一下上传图片和文本的代码,完整前后端。
这里我准备了一个demo,需要的可以直接复制
这是富文本编辑器的效果图
在这里插入图片描述
下面附上js代码,包括提交图片和文本
接下里是Django后端的接收代码
from django.shortcuts import render,redirect,HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exemp
@login_required
@csrf_exempt
def 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_exempt
def 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
希望对您有所帮助。有疑问可以留言。