django-ckeditor上传图片到阿里云OSS
参考信息
资料1: django_ckeditor上传图片到七牛云OSS
使用
1. 安装django-ckeditor 【参考 资料1】
2. setting.py配置INSTALLED_APPS 【参考 资料1】
3. 编写ckeditor_storage.py
class AliyunStorageObject(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):
"""
上传文件到阿里云
"""
# 构建对象
bucket = oss2.Bucket(oss2.Auth(ALIYUN_ACCESS_KEY_ID, ALIYUN_ACCESS_KEY_SECRET), ALIYUN_END_POINT, ALIYUN_BUCKET_NAME)
self.file = content
file_data = content.file
file_name = self._new_name(name)
info = bucket.put_object(file_name, file_data.read())
if info.status == 200:
base_url = bucket.sign_url('GET', file_name, 60*60*24)
# 表示上传成功, 返回文件名
return base_url
else:
# 上传失败
logger.error(f'{info.error}')
raise Exception("上传阿里云失败")
def exists(self, name):
# 验证文件是否存在,因为会去生成一个新的名字存储到七牛,所以没有必要验证
return False
def url(self, name):
# 上传完之后,已经返回的是全路径了
return name
4. setting.py中设置ckeditor
# 图片保存路径
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/media/'
X_FRAME_OPTIONS = 'SAMEORIGIN'
# 阿里云OSS相关配置
ALIYUN_ACCESS_KEY_ID = ""
ALIYUN_ACCESS_KEY_SECRET = ""
ALIYUN_END_POINT = ""
ALIYUN_BUCKET_NAME = ""
ALIYUN_OSS_CNAME = "" # 自定义域名,如果不需要可以不填写
ALIYUN_BUCKET_ACL_TYPE = "public-read" # private, public-read, public-read-write
# OSS配置
DEFAULT_FILE_STORAGE = 'blog.ckeditor_storage.AliyunStorageObject'
5. setting.py中配置功能项和样式 【参考 资料1】
6. 设置model.py 【参考 资料1】
7. 设置urls.py 【参考 资料1】
8. 测试
Hole yor life get everything if you never give up.