Django使用tinyMCE图片上传

前言

之前完成了Django使用tinyMCE编辑富文本功能,但是在实际的环境中还需要上传图片的功能。tinyMCE对图片的上传也是支持的。

在查询相关文档后可以开始完成这一功能。

步骤

在tinyMCE中配置文件上传路径

tinymce.init({
  selector: 'textarea',  // change this value according to your HTML
  images_upload_url: '/blog/upload/image/' # Django路由中图片上传地址
});

编写Django接收文件

from django.views.decorators.csrf import csrf_exempt
from xiangmuming.settings import BLOG_IMAGE_UPLOAD, DONAME # 一个文件存储路径 比如/static/images/  DONAME 域名
@csrf_exempt # 防止post的时候引发403
def uploadImage(request):
    if request.method == "POST":
        f = request.FILES['file']
        file_name_suffix = f.name.split(".")[-1]
        if file_name_suffix not in ["jpg", "png", "gif", "jpeg", ]:
            return JsonResponse({"massage":"错误的文件格式"})
        upload_time = time.localtime()
        path = os.path.join(
            BLOG_IMAGE_UPLOAD,
            time.strftime("%Y", upload_time),
            time.strftime("%m", upload_time),
            time.strftime("%d", upload_time),
        )
        # 如果没有这个路径创建之
        if not os.path.exists(path):
            os.makedirs(path)
        file_path = os.path.join(path, f.name)

        if os.path.exists(file_path):
            return JsonResponse({
                "massage":"文件已存在",
                # src 为访问图片的完整路径,这里写src是为后面的判断
                "src": DONAME+"/static"+file_path.split("upload")[-1].replace("\\", "/"),
            })
        with open(file_path, 'wb+') as destination:
            for chunk in f.chunks():
                destination.write(chunk)

        return JsonResponse({
            # location 为访问图片的完整路径
            "location": DONAME+"/static"+file_path.split("upload")[-1].replace("\\", "/")
        })
    return HttpResponse("错误的请求")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值