本人使用的是 Django 的自带的管理后台,安装 ckeditor 富文本编辑器后,上传图片的时候直接传到七牛云。
1. python 3.6.8
2. django==1.11.21
3. django-ckeditor==5.3.1
4. qiniu==7.2.6
# joyoo\blog\ckeditor_storage.py ( joyoo 为项目名),需要 注册七牛云账号,并绑定域名空间
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@site: http://zhuoqun.info/
@email: yin@zhuoqun.info
@time: 2019/7/9 16:57
"""
import datetime
import uuid
from django.core.files.storage import Storage
from qiniu import Auth, put_data
from joyoo.settings import QINIU_ACCESS_KEY, QINIU_SECRET_KEY, QINIU_BUCKET_DOMAIN, QINIU_BUCKET_NAME
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(QINIU_ACCESS_KEY, QINIU_SECRET_KEY)
token = q.upload_token(QINIU_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_BUCKET_DOMAIN, ret.get("key"))
# 表示上传成功, 返回文件名
return base_url
else:
# 上传失败
raise Exception("上传七牛失败")
def exists(self, name):
# 验证文件是否存在,因为会去生成一个新的名字存储到七牛,所以没有必要验证
return False
def url(self, name):
# 上传完之后,已经返回的是全路径了
return name
# joyoo\joyoo\settings.py( joyoo 为项目名)
INSTALLED_APPS = [
'ckeditor',
'ckeditor_uploader',
]
CKEDITOR_UPLOAD_PATH = '' # 图片ckeditor文件上传路径, 这里使用七牛云存储,不填
CKEDITOR_JQUERY_URL = '//cdn.bootcss.com/jquery/1.11.3/jquery.min.js'
# CKEDITOR_IMAGE_BACKEND = 'pillow' # 注释掉就是禁止生成缩略图,传七牛云要注释掉
DEFAULT_FILE_STORAGE = 'blog.ckeditor_storage.StorageObject' # app名称.app下的文件名称.类名
# 七牛云相关配置
QINIU_ACCESS_KEY = ''
QINIU_SECRET_KEY = ''
QINIU_BUCKET_DOMAIN = ''
QINIU_BUCKET_NAME = ''