vue网页小程序实现七牛云图片文件上传以及原生组件video显示不出问题

七牛云图片、文件上传


⭐vue网页端


一般vue项目搭载 element-ui,因此我们直接采用 el-upload 组件实现图片、文件上传。本文以图片上传为例


① 获取七牛云上传参数,即上传所需token


在methods里面定义一个方法 getQiniuToken


// 获取七牛云上传参数
getQiniuToken{
    // 这里采用axios调取接口, baseUrl即为接口请求服务器地址
 this.$axios.post(baseUrl+'api/upload_qiniu_get_token',{
    }).then((res) => {
     // 下面保存参数,视具体接口而变
    var data = res.data;
    if(data.error_code == 0){
        this.uploadData = {
        	token:data.token // 获取上传token
    	}
    	this.img_domain = data.host; // 保存图片前缀
    }
    }).catch((err) => {

    });
}

el-upload 组件使用


action参数:根据存储区域会有相应的上传地址,


data参数: 上传所需参数即 {token: xxx}


  <el-upload
      action="https://upload-z2.qiniup.com"
      :data="uploadData"
      :show-file-list="false"
      accept="image/*"
      :on-success="handleSuccess">
      <el-image
          style="width: 100px; height: 100px"
          :src="img"
          fit="cover">
          <div slot="error" class="image-slot">
          	<i class="el-icon-picture-outline"></i>
          </div>
      </el-image>
  </el-upload>

③上传成功,保存地址,借助 el-image展示图片


handleSuccess(res){
    this.img = this.img_domain + res.key; 
    // res.key是上传七牛云服务器后换来的凭证,拼接图片前缀,即可展示图片
}

⭐小程序版


上传图片


① 获取七牛云参数


// 获取七牛云参数
  getQiniuToken(){
    let that = this
    // 请求接口
    request.request('get','api/upload_qiniu_get_token',{
      
    },function(res){
      console.log(res)
      if (res.error_code == 0) {
        that.setData({
          token: res.data.token  // 将上传token保存下来
        })
      }
      else{
        wx.showToast({
          title: res.error_message,
          icon : 'none'
        })
      }
    },(err)=>{
    })
  },

② 上传图片


<!-- 上传图片展示的地方imgs -->
<view class="item" wx:for="{{imgs}}" wx:key="index">
   <image class="pic" bindtap="previewImg" data-index="{{index}}" src="{{item}}"></image>
   <image class="close" bindtap="delImg" data-index="{{index}}" src="/images/muban/close.png"></image>
</view>

<!-- 随便来张图片充当一下上传按钮即可 -->
<view class="item" bindtap="uploadImg">
	<image class="pic" src="/images/add_pic.png"></image>
</view>

uploadImg方法


// 调用微信选择图片api  
uploadImg() {
	let that = this
	wx.chooseImage({
      count: 9,
      success (res) {
          console.log(res)
          // tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths
          // 显示加载
           wx.showLoading({
            title: '玩命加载中',
          })
          // 实现多图片上传
          for(let i=0;i<tempFilePaths.length;i++){
              wx.uploadFile({
                  url: 'https://up-z2.qiniup.com', // 七牛云上传地址
                  filePath: tempFilePaths[i],
                  name: 'file',
                  formData: {
                  'token': that.data.token, // 上传token
                  },
                  success (res){
                      console.log(res)
                      let domain = that.data.img_domain
                      const data = JSON.parse(res.data)
                      that.data.imgs.push(domain + data.key) //拼接图片
                      that.setData({
                          imgs: that.data.imgs 
                      })
                     
                  },
                  complete(){
                      if(i == tempFilePaths.length-1){
                          wx.hideLoading()
                      }
                  }
              })
          }
       }
    })
}

previewImg预览图片


// 点击放大预览图片
previewImg(e){
     var index = e.currentTarget.dataset.index;
	 wx.previewImage({
        current: this.data.imgs[index], 
        urls: this.data.imgs
    })
}

delImg删除图片


  // 删除图片
  delImg(e){
    var index = e.currentTarget.dataset.index;
    this.data.imgs.splice(index,1);
    this.setData({
        imgs: this.data.imgs
    })
  },

上传视频


与上传图片类似,这里就贴一下上传的方法好啦


 // 上传视频
  uploadVideo(e){
    let that = this
    wx.chooseVideo({
      success (res) {
          const tempFilePaths = res.tempFilePath
          console.log(res)
          // 显示加载
           wx.showLoading({
            title: '玩命加载中',
          })
          wx.uploadFile({
              url: 'https://upload-z2.qiniup.com', 
              filePath: tempFilePaths,
              name: 'file',
              formData: {
                  'token': that.data.token
              },
              success (res){
                  console.log(res)
                  let domain = that.data.video_domain
                  const data = JSON.parse(res.data)
                  that.data.videos.push(domain + data.key)
                  that.setData({
                      videos: that.data.videos
                  })
              },
              complete(){
                  wx.hideLoading()
              }
          })
      }
  	})
  },

预览视频失败解决


有些时候会遇到直接点击 video微信原生组件会出现黑屏或不显示问题,这边推荐使用小程序的 previewMedia 接口来实现预览


<view class="item" wx:for="{{videos}}" wx:key="index">
    <video class="pic" bindtap="onPreviewVideo" data-url="{{item}}" src="{{item}}"></video>
    <image class="close" bindtap="delVideo" data-index="{{index}}" src="/images/muban/close.png"></image>
</view>

 // 预览视频
  onPreviewVideo(e){
    // 获取视频地址
    let urls = e.currentTarget.dataset.url
    console.log(urls)
    wx.previewMedia({
      sources: [{
        url: urls,
        type: 'video',
        poster:'https://i.loli.net/2021/08/26/vhdxCoH3wUq9nZz.png' // 预览图,随喜好来,不写也没事
      }],
      current: 0,
      fail() {
        wx.showToast({ title: '预览视频失败', icon: 'none' });
      },
    });
  },
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 中使用七牛云进行图片上传,需要先在七牛云申请一个空间并获取 Access Key 和 Secret Key,然后安装相关的依赖库。 1. 安装依赖库: ``` npm install qiniu-js vue-qiniu-upload --save ``` 2. 在 Vue 中引入依赖: ``` import QiniuUpload from 'vue-qiniu-upload' import * as qiniu from 'qiniu-js' ``` 3. 在 Vue 组件中使用: ``` <template> <div> <qiniu-upload :domain="domain" :access-key="accessKey" :secret-key="secretKey" :path="path" :size="size" :accept="accept" :before="beforeUpload" :complete="uploadComplete" :error="uploadError" > <button>上传图片</button> </qiniu-upload> </div> </template> <script> export default { components: { QiniuUpload }, data () { return { domain: 'your-qiniu-domain', accessKey: 'your-access-key', secretKey: 'your-secret-key', path: '/upload', size: 10 * 1024 * 1024, accept: 'image/*' } }, methods: { beforeUpload (file) { // 可以在这里进行一些上传前的操作,比如图片压缩等 }, uploadComplete (res) { // 上传完成后的回调 console.log('上传完成', res) }, uploadError (err) { // 上传失败的回调 console.log('上传失败', err) } } } </script> ``` 以上代码中,`QiniuUpload` 组件是我们刚才引入的依赖库中提供的,通过传入相关参数就可以进行图片上传了。在 `beforeUpload` 方法中可以对图片进行一些处理,比如压缩等操作。`uploadComplete` 和 `uploadError` 分别是上传成功和上传失败后的回调函数,可以进行一些相关的操作。 注意,上传图片之前需要在七牛云中进行配置,具体可以参考七牛云的文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值