随笔 - 5  文章 - 0  评论 - 6  阅读 - 4343

前端图片上传七牛云

1.图片上传到七牛云,必须要注册登录七牛云账号,然后在上面创建一个空间。

2.为了实现上传,必须要有一个域名,这里使用CDN测试域名。然后在“密钥管理”获取AccessKey和SecretKey,记住自己命名空间。

获取AccessKey和SecretKey

3.使用七牛云提供的接口实现数据上传
<script src="https://unpkg.com/qiniu-js@2.4.0/dist/qiniu.min.js"></script>

4.通过提供的AccessKey和SecretKey,BUCKET就是自己的命名空间,生成token。

点击查看代码
const getQiniuToken = (req, res) => {
  const mac = new qiniu.auth.digest.Mac(ACCESS_KEY, SECRET_KEY)
  const options = {
    scope: BUCKET
  }
  const putPolicy = new qiniu.rs.PutPolicy(options)
  const token = putPolicy.uploadToken(mac)
  return res.json({
    code: 200,
    data: token,
    msg: 'success'
  })
}

5.通过生成的token,便可以将数据发送到自己的七牛云空间,实现发送过程。

点击查看代码
uploadQiniu(e) {
      const guid = genGuid()
      const [file] = e.target.files
      typeof this.getLocalUrl === 'function' && this.createObjetURL(file, guid)

      const fileType = file.type && file.type.split("/")[1]
      const fileSize = file.size / 1024 / 1024
      if (fileSize > 1) {
        this.$message.error('只能上传小于1M的图片!换一个小图片试试吧~~')
        return
      }
      const putExtra = {
        fname: "",
        params: "",
        mineType: ["image/png", "image/jpeg", "image/gif"]
      }
      const config = {
        useCdnDomain: true
      }
      const error = (err) => {
        this.getStatus({status: uploadImgStatusMap.error, data: err, guid})
      }
      const next = (res) => {
        this.getStatus({status: uploadImgStatusMap.next, data: res, guid})
      }
      const complete = (res) => {
        console.log(res)
        this.getStatus({status: uploadImgStatusMap.complete, data: res, guid})
      }
      const subObject = {
        next,
        error,
        complete
      }
      const imgName = imgRandomName() + '.' + fileType
      const observable = window.qiniu.upload(file, imgName, this.token, putExtra, config)
      const subScription = observable.subscribe(subObject)
      console.log(subScription)
    },
posted on   浩瀚星辰一粒沙  阅读(1026)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示