实名认证成功之后,赠送10G存储空间
复制粘贴AK和SK
创建存储空间,填写空间名称,选择存储区域。访问控制选择位公开空间
获取测试域名
安装qiniu
# 在虚拟机中安装七牛云所需模块
pip install qiniu
- 配置文件
# 创建utils/secrets/qiniu_secret_info.py文件
# 从七牛云"个人中心>密钥管理"中获取自己的 Access Key 和 Secret Key
QI_NIU_ACCESS_KEY = '你自己七牛云上的AK'
QI_NIU_SECRET_KEY = '你自己七牛云上的SK'
QI_NIU_BUCKET_NAME = '你自己在七牛云上创建的存储空间名'
- 视图代码
# 将图片上传到七牛云,需要后端返回token
import qiniu
from utils.secrets import qiniu_secret_info
class UploadToken(PermissionRequiredMixin, View):
"""
"""
permission_required = ('news.add_news','news.view_news')
def handle_no_permission(self):
return to_json_data(errno=Code.ROLEERR, errmsg='没有相关权限')
def get(self, request):
access_key = qiniu_secret_info.QI_NIU_ACCESS_KEY
secret_key = qiniu_secret_info.QI_NIU_SECRET_KEY
bucket_name = qiniu_secret_info.QI_NIU_BUCKET_NAME
# 构建鉴权对象
q = qiniu.Auth(access_key, secret_key)
token = q.upload_token(bucket_name)
# 最好直接返回原生js
return JsonResponse({"uptoken": token})
- 前端js
// ================== 上传至七牛(云存储平台) ================
let $progressBar = $(".progress-bar");
QINIU.upload({
"domain": "http://pl3yncr1e.bkt.clouddn.com/", // 七牛空间域名
"uptoken_url": "/admin/token/", // 后台返回 token的地址
"browse_btn": "upload-btn", // 按钮
"success": function (up, file, info) { // 成功
let domain = up.getOption('domain');
let res = JSON.parse(info);
let filePath = domain + res.key;
console.log(filePath);
$thumbnailUrl.val('');
$thumbnailUrl.val(filePath);
},
"error": function (up, err, errTip) {
// console.log('error');
console.log(up);
console.log(err);
console.log(errTip);
// console.log('error');
message.showError(errTip);
},
"progress": function (up, file) {
let percent = file.percent;
$progressBar.parent().css("display", 'block');
$progressBar.css("width", percent + '%');
$progressBar.text(parseInt(percent) + '%');
},
"complete": function () {
$progressBar.parent().css("display", 'none');
$progressBar.css("width", '0%');
$progressBar.text('0%');
}
});