django 利用kindeditor 前端上传图片

项目使用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 文件就好了

参考   官方文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Django 中,可以通过一个 `ImageField` 字段来接收上传的图片,并将其保存到指定的目录下。与 `FileField` 类似,`ImageField` 字段也会自动检查上传的文件是否为图片,并对其进行处理。 首先,在模型中定义一个 `ImageField` 字段,例如: ```python class MyModel(models.Model): uploaded_image = models.ImageField(upload_to='uploads/') ``` 在这个例子中,`uploaded_image` 是一个 `ImageField` 字段,`upload_to` 参数指定了图片的保存路径。当用户上传图片时,Django 会自动将图片保存到指定的路径下,并将图片的相关信息保存到数据库中。 在视图函数中,我们可以通过 `request.FILES` 属性获取上传的图片,然后将其保存到指定的位置。例如: ```python def upload_image(request): if request.method == 'POST': uploaded_image = request.FILES['image'] # 将图片保存到指定的路径下 file_path = os.path.join(settings.MEDIA_ROOT, 'uploads', uploaded_image.name) with open(file_path, 'wb+') as f: for chunk in uploaded_image.chunks(): f.write(chunk) # 创建 MyModel 对象,并保存图片的相关信息到数据库中 my_model = MyModel.objects.create(uploaded_image=file_path) # 处理图片 # ... return render(request, 'upload.html') ``` 在这个例子中,我们首先获取上传的图片,然后将其保存到指定的路径下。接着,我们创建一个 `MyModel` 对象,并将保存图片的路径保存到 `uploaded_image` 字段中,最后保存对象到数据库中。需要注意的是,保存图片到指定路径后,我们需要将图片的路径保存到数据库中,而不是直接保存图片的二进制数据。 需要注意的是,在保存图片时,Django 会自动检查上传的文件是否为图片,并对其进行处理。如果上传的不是图片Django 会抛出一个 `ValidationError` 异常。因此,在处理图片时,需要使用 `try...except` 块来捕获可能出现的异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值