七牛云上传文件 - 邱乘屹的个人技术博客

为什么使用七牛云?

使用第三方提供的七牛云是很有必要的
在项目开发过程中,如果将用户上传的文件,图片,音频等等放到项目中,将会使项目越来越臃肿,而且会严重影响性能。并且,如果将文件存到本地,需要进行不断的维护,占用空间,当出现宕机等情况,造成数据丢失,这是不能允许的
而把这些文件放到第三方云,就不会出现这种问题,只需要通过简单的配置,便可以永久保存,减少服务器压力,也不用害怕因宕机出现数据丢失的情况。

如何使用

安装第三方七牛云

pip install qiniu

django获取七牛云token 代码如下

# 定义七牛云 存储接口
from qiniu import Auth

class QiNiu(APIView):
    def get(self,request):
        # 定义密钥
        q = Auth('公钥,'私钥')
        # 指定上传空间
        token = q.upload_token('updateli')
        print(token)
        return Response({
            'code':200,
            'token':token
        })

上传

这里我编写了一个测试项目供大家参考


<template>
  <div>
       <Form>
          <FormItem label="图片">
              <input type="file" @change="update">
          </FormItem>
        <!--头像-->
        <Avatar :src="img" :width="150" fit="'fill"></Avatar>
          
          
          
      </Form>
  </div>
</template>

<script>
export default {
    data(){
        return{
            name:'',
            price:'',
            img:'',
            //七牛云上传凭证
            uptoken:''

        }
    },
    methods: {
        
       //上传七牛云
       update(e){
           console.log(this.uptoken)

           //获取文件对象
           let file = e.target.files[0];
           //声明参数
           let param = new FormData()

           //将上传凭证添加参数
           param.append('token',this.uptoken)

           //附加文件
           param.append('file',file)

           //定制化axios 不让带cokkie
           const axios_qiniu = this.axios.create({withCredentials:false});
           
           //发送请求
           axios_qiniu({
               method:'POST',
               url:'http://up-z1.qiniu.com/',
               data:param,
               timeout:3000,




           }).then(res=>{

               console.log(res)
               //进行辅助
               this.img = '在七牛云储存空间中绑定的域名' + res.data.key;


           })



       },



       //获取七牛云上传凭证
       get_uptoken(){
           this.axios.get('http://localhost:8000/uptoken/').then((res)=>{
               console.log(res)
               this.uptoken = res.data.token

           })
       }
        
    },
    mounted() {
        //获取uptoken
        this.get_uptoken()
    },
}
</script>

<style>

</style>

猜你喜欢

转载自blog.csdn.net/weixin_47074764/article/details/106537077
今日推荐