廖鑫豪的个人博客

@lxhcool

男,爱好女

文章 8
朋友 7
来访 11

工具

框架

灵感

社区

资源

酷站

RANKINGS

    • 杭州
    • https://www.lxhcool.cn
    • 网站成立551天

    lxhcool

    • 默认

    vue 中 使用 qiniu-js 实现 上传图片到七牛云

    项目安装qiniu-js

    npm i qiniu-js --save

    main.js中引用

    import * as qiniu from 'qiniu-js'
    Vue.use(qiniu)

    项目页面使用

    1.请求后端接口,获取七牛token,以及域名

    2.使用获取的token进行操作

    3.哼,垃圾东西

    <template>
      <div class="container">
        <div class="form-wrap">
          <div class="license">
            <span>图片</span>
            <div class="license-img-box">
              <input
                ref="upload"
                id="upload"
                type="file"
                class="upload-img"
                @change="uploadImg"
              />
              <img :src="licenseImg" alt="">
            </div>
          </div>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      data () {
        return {
          qiNiuData: {
            key: '',
            token: ''
          },
          domain: '',
          licenseImg: '',
        }
      },
      methods: {
        uploadImg (event) {
          let file = event.target.files[0]
          let key = file.name
          let token = this.qiNiuData.token
          let putExtra = {
            fname: file,
            params: {},
            mimeType: ['image/png', 'image/jpeg', 'image/gif', 'image/jpg']
          }
          let config = {
            useCdnDomain: true,
            region: qiniu.region.z0
          }
          let observer = {
            next (res) {
              console.log('已上传大小,单位为字节:' + res.total.loaded)
              console.log('本次上传的总量控制信息,单位为字节:' + res.total.size)
              console.log('当前上传进度,范围:0~100:' + res.total.percent)
            },
            error (err) {
              console.log(err.code)
              console.log(err.message)
              console.log(err.isRequestError)
              console.log(err.reqId)
            },
            complete: (res) => {
              console.log(res)
              this.licenseImg = this.domain + res.key
            }
          }
          let observable = qiniu.upload(file, key, token, putExtra, config)
          let subscription = observable.subscribe(observer)
        },
        // 请求七牛云token
        async getqiniuToken () {
          try {
            let res = await this.$api.getqiniuToken()
            this.qiNiuData.token = res.data.token
            this.domain = res.data.domain
          } catch (error) {
            console.log(error)
          }
        }
      },
      mounted () {
        this.getqiniuToken()
      }
    }
    </script>
    

     

     

     

     

    Comments | NOTHING

      游客,你好 修改资料

    *邮箱和昵称必须填写