vue中使用七牛图片上传

vue中使用七牛图片上传

引入七牛

npm(cnpm) install --save qiniu
复制代码

项目引入七牛进项使用

import Qiniu from 'qiniu.js'
复制代码

html代码使用

定义input标签接收上传的图片地址

 <div style="margin-left:10px;">
    <input ref="imgLocal" class="input-loc-img" name="imgLocal" id="imgLocal" type='file' accept="image/*">
    <span @click="updateer">上传</span>
  </div>
复制代码

js代码使用 图片上传

  //url 七牛部署的地址
  // bucket参数为七牛的空间名 
  // this.$refs.imgLocal.files[0] 为上传的图片的名包含路径
  // res返回数据为一个key,通过key可以获取上传到七牛上的图片地址 
  // 图片上传凭证
  updateer() {
  //  bucket:‘public-image’(可直接拼接图片地址)
    axios.post('url', { bucket: '' }).then((res) => {
      const uploadToken = res.data.upToken;
      var data = new FormData();
      data.append('token', uploadToken);
      data.append('file', this.$refs.imgLocal.files[0]);
      axios({
        method: 'POST',
        url: 'http://up.qiniu.com',
        data: data,
        onUploadProgress: function (progressEvent) {
          var percentCompleted = Math.round(progressEvent.loaded * 100 / progressEvent.total);
        },
      }).then((res) => {
        //  `http://publicimage.xq5.com/${response.data.key}`; (若bucket 参数为public-image则不需要下一步的图片地址获取可直接使用http://publicimage.xq5.com/ + ‘res.data.key’,拼接图片地址)
        console.log(res.data.key)
      })
    });
  },
复制代码

图片地址的获取

  // url 七牛部署的地址
  // bucket参数为七牛的空间名  file_name参数为上传图片获取到的 key
  // 返回数据为带有http的图片地址
  axios.post(url, { bucket: '', file_name:'' }).then((res) => {
    if (Number(res.data.errno) === 0) {
      console.log(res.data.qrcodeURL)
    }
  });
复制代码

说明

若有公共地址上传图片,则可通过域名加key拼接图片地址进行访问图片地址

转载于:https://juejin.im/post/5afea240f265da0b886daa49

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值