七牛云上传的步骤
-
前端请求后端,获取上传
七牛云
的token -
将后端返回的token放入提交的表单中
-
设置el-upload中的上传地址,即action(七牛云对应的服务器地址) action="http(s)://up-z2.qiniup.com"
-
选择图片,进行自动上传-->:auto-upload='true'
-
上传成功的处理,拼接可访问图片的路径,==自己的域名(30天有效)==+ res.key
首先在django后端定义端口
from qiniu import Auth
# 需要填写你的 Access Key 和 Secret Key
access_key = 'hmv--oUg0_Ubsrq**********VRfYkpmmSa1b_bv'
secret_key = '9tW8bwz3VQonIUb********pp8rayHZTv_oZGIrh'
# 构建鉴权对象
def qn_token():
q = Auth(access_key, secret_key)
# 要上传的空间,你的存储空间
bucket_name = 'pzc'
# 生成上传 Token
token = q.upload_token(bucket_name)
return token
# 生成上传七牛云的token
class QiNiuTokenView(APIView):
"""
获取七牛云上传token
"""
def get(self, request):
token = qn_token()
return Response({'msg': 'OK', 'code': 200, 'qn_token': token})
在vscode中用vue2和el-element实现
<template>
<div>
<div>
<el-upload
(使用自己选择的存储区域,此处是华北河北)
action="http://upload-z1.qiniup.com"
:auto-upload="true"
:on-success="uploadSuccess"
:data="upload_data"
:on-error="uploadError"
>
<el-button size="small" type="primary">点击选择图片</el-button>
</el-upload>
</div>
</div>
</template>
<script>
export default {
name: "",
data() {
return {
upload_data: {
token: "",
},
imgUrl: "",
//生成的外链域名
baseUrl: "http://rhemeztul.hb-bkt.clouddn.com/",
};
},
props: {},
components: {},
created() {},
mounted() {
this.get_token();
},
methods: {
//获取七牛token
get_token() {
this.$axios
.get("/qn_token/")
.then((dat) => {
console.log("token>>>", dat.data);
this.upload_data.token = dat.data.qn_token;
})
.catch((err) => {
console.log(err.response);
});
},
//上传成功后执行的代码
uploadSuccess(res, files) {
console.log("上传后的结果是>>>", res);
console.log("上传后文件的结果是>>>", files);
this.imgUrl = this.baseUrl + res.key;
console.log("imgurl>>>", this.imgUrl);
this.$router.push('/demo2')
},
//上传失败后执行的代码
uploadError(err) {
console.log("失败", err);
},
},
computed: {},
watch: {},
directives: {},
filters: {},
};
</script>
<style ></style>
提交图片会自动上传到七牛云自己的仓库里