博客文章图片:Django使用ckeditor上传到七牛云

因为博客用的富文本编辑器, 文章博客图片想通过第三方存储, 这样可以通过cdn获取以加速网站打开速度, 搜索部分资料发现这个篇文章不错

介绍

最近正在使用Django开发一个项目,有一个需求是需要在后台,使用富文本编辑器,去自定义一些内容。会涉及到图片的上传。我准备把上传的内容存储到七牛里面,不想放在服务器上面。碰到一些问题,总结一下。

分析

我使用的django-ckeditor版本为5.6.1。前面操作都是跟官网说的一样。

  • 在setting.py里面的INSTALLED_APPS增加:
'ckeditor',  # 富文本编辑器
'ckeditor_uploader'  # 富文本编辑器上传图片模块

增加upload_path

CKEDITOR_UPLOAD_PATH = "uploads/"
  • 在model里面对相应的字段,使用ckeditor_uploader。
from ckeditor_uploader.fields import RichTextUploadingField
content = RichTextUploadingField(verbose_name='内容')
  • 重点来了,那我怎么拿到我上传的文件或图片呢,比如我要传到七牛。通过查看ckeditor_uploader的源码,我们发现有一个路由配置文件ckeditor_uploader/urls.py

很好奇的查看upload做了什么事

大概的阅读了一下,发现这个地方就是处理用户上传文件的时候,其中保存文件是在self._save_file(request, uploaded_file)这个方法里面操作的。继续往下面看

看到这个storage就有点熟悉了,django也有提供,难道是一个东西?

到这边就已经很明白了,如果我们不在setting里面定义storage的话,就默认用的django的storage。

方案

分析完代码之后,我大概理了一下思路,我想了想一共有两种方法,可以去解决:

  1. 在setting里面配置CKEDITOR_STORAGE_BACKEND

这个是比较简单的,也是官方推荐我们用的方法,我们只需要处理上传的地方就可以了。只需要写个class把django.core.files.storage封装一下就可以。

from django.core.files.storage import Storage


class StorageObject(Storage):
    def __init__(self):
        self.now = datetime.datetime.now()
        self.file = None

    def _new_name(self, name):
        new_name = "file/{0}/{1}.{2}".format(self.now.strftime("%Y/%m/%d"), str(uuid.uuid4()).replace('-', ''),
                                             name.split(".").pop())
        return new_name

    def _open(self, name, mode):
        return self.file

    def _save(self, name, content):
        """
        上传文件到七牛
        """
        # 构建鉴权对象
        q = Auth(access_key, secret_key)
        token = q.upload_token(bucket_name)
        self.file = content
        file_data = content.file
        ret, info = put_data(token, self._new_name(name), file_data.read())

        if info.status_code == 200:
            base_url = 'http://%s/%s' % (QINIU_URL_DOMAIN, ret.get("key"))
            # 表示上传成功, 返回文件名
            return base_url
        else:
            # 上传失败
            raise Exception("上传七牛失败")

    def exists(self, name):
        # 验证文件是否存在,因为我这边会去生成一个新的名字去存储到七牛,所以没有必要验证
        return False

    def url(self, name):
        # 上传完之后,已经返回的是全路径了
        return name

然后在setting里面配置

CKEDITOR_STORAGE_BACKEND = 'common.storage.StorageObject'

就可以了。

2. 第二个方法就比较抽象了,在写url的时候,直接把ckeditor/upload用我们自己的方法来代替。

urlpatterns = [
    path('ckeditor/upload/', staff_member_required(csrf_exempt(CkeditorView.as_view())), name='ckeditor_upload'),
]

然后写一个view

class CkeditorView(generic.View):
    permission_classes = [IsAuthenticated]
    http_method_names = ['post']

    def post(self, request, **kwargs):
        uploaded_file = request.FILES['upload']

        backend = image_processing.get_backend()

        ck_func_num = request.GET.get('CKEditorFuncNum')
        if ck_func_num:
            ck_func_num = escape(ck_func_num)

        # Throws an error when an non-image file are uploaded.
        if not getattr(settings, 'CKEDITOR_ALLOW_NONIMAGE_FILES', True):
            try:
                backend.image_verify(uploaded_file)
            except utils.NotAnImageException:
                return HttpResponse("""
                    <script type='text/javascript'>
                    window.parent.CKEDITOR.tools.callFunction({0}, '', 'Invalid file type.');
                    </script>""".format(ck_func_num))
        # 存储文件
        url = storage(uploaded_file)

        if ck_func_num:
            # Respond with Javascript sending ckeditor upload url.
            return HttpResponse("""
            <script type='text/javascript'>
                window.parent.CKEDITOR.tools.callFunction({0}, '{1}');
            </script>""".format(ck_func_num, url))
        else:
            retdata = {'url': url, 'uploaded': '1',
                       'fileName': uploaded_file.name}
            return JsonResponse(retdata)

这样的话,就可以了。

这个方法不太建议,一般我们没有必要去修改整个post的过程,只需要动到upload file这个过程就可以了。

结论

就上面两个方案,我建议使用第一个,简单方便。
秀一下成果

发布了160 篇原创文章 · 获赞 21 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/weixin_43064185/article/details/105275929