微信云函数+七牛云视频上传+转码压缩

不得不说 七牛云的开发文档狗看了直摇头。。。耗时两天,虽然最后这个功能pass掉了。但是在这里做个记录把。

//上传的图片方法。	

// wx.cloud.callFunction({
		// 	name:"qiniuyun",

		// 	success(res){
		// 		// console.log(res.result.token)
		// 		that.token=res.result.token;
		// 		uni.chooseImage({
		// 			count: 1, //默认9
		// 			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
		// 			sourceType: ['album'], //从相册选择
		// 			success: function (res) {
		// 				let data = res.tempFilePaths
		// 				data.forEach(e=>{
		// 					that.upload(e)
		// 				 })

		// 			}
		// 		});

		// 	},fail(res){
		// 		console.log(res);
		// 	}
		// })
		


//上传视频

upload() {
  let that = this;
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '正在上传',
      mask: true
    });
	console.log(that.urls);
    wx.uploadFile({
      url: 'https://upload-z2.qiniup.com', //这个是服务器的地址, 就是你七牛云的服务器 我这个是在华南 
      filePath: that.urls, // 上传文件路径
      header: {
        'Content-Type':'multipart/form-data'
      },
      name: 'file', // 上传文件名称
      formData: {
        token: that.token, // 上传凭证             //要记住formData前端只能上传这两个
        key:that.key,   //必须从后端获取  云函数中获取
      },
      success: function(res) {
        resolve(res);
      },
      fail: function(res) {
        // 上传失败,返回错误信息
        reject(res.errMsg);
      }
    });
  });




qiniuyun() {
  let that = this;
   that.key = new Date().getTime() + '.mp4';
  wx.cloud.callFunction({
    name: 'qiniuyun',
	data:{
		functionName:"uploadShipin",
		key:that.key
	},
    success(res) {
      that.token = res.result.token;
      wx.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 10,
        camera: 'back',
        success: function(res) {
          that.dataURL = res.tempFilePath;
          wx.showLoading({
            title: '正在上传',
            mask: true
          });
          // 调用上传函数,等待七牛云存储的返回值
          that.upload()
            .then(key => {
			  that.persistenID=JSON.parse(key.data).persistentId;             // console.log('上传成功,文件路径为:', persistenID);      //为什么persistenID  因为上传后 我还进行了转码, 由于微信云函数 建立一个http服务挺难的,所以需要主动轮询去查询转码进度, 后面我会说。 如果不是微信云函数 可以用七牛云自带的api 持久化URL那个,那个会自动返回更加好
				wx.cloud.callFunction({
					name:"qiniuyun",
					data:{
						functionName:"checkTranscodeProgress",
					persistentId:that.persistenID	
					},
					success(res){
						console.log(res.result);
						  wx.hideLoading();
					},fail(res){
						console.log(res);
						  wx.hideLoading();
					}
				})
              // console.log('上传成功,文件路径为:', persistenID);
            })
            .catch(errMsg => {
              wx.hideLoading();
              console.log('上传失败,错误信息为:', errMsg);
            });
        }
      });
    },
    fail(res) {
      console.log(res);
    }
  });
},
微信云函数

const cloud = require('wx-server-sdk')
const qiniu = require('qiniu')



//查询转码结果
async function uploadShipin(key) {
// var accessKey = '在控制台看';
// var secretKey = '在七牛云控制台看';
  var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
// const bucket = '你的空间名字';
  const Buffer = require('buffer').Buffer;
  this.key =`video/${key}`;
  const encodedEntryURI = Buffer.from(`${bucket}:${key}`).toString('base64').replace(/\+/g, '-').replace(/\//g, '_');
  var options = {
    scope:bucket,
    deadline: 3600,
    persistentOps: `avthumb/mp4/vb/2000k/ab/128k/ar/44100/acodec/libfaac/r/30/vcodec/libx264/s/1280x720|saveas/${encodedEntryURI}  //另存的地址和转码的格式。  持久化
    `,
     // 指定转码管道
     persistentPipeline: 'gaoqing',
     force:1,
     returnBody: '{"key": $(key), "hash": $(etag), "fsize": $(fsize), "bucket": $(bucket), "name": $(fname),"persistentId":$(persistentId)}'
//由于是在微信云函数 所以需要在这里返回一个持久化id  就如我前面所说的   需要主动轮询 因为http服务在微信云函数挺难的
    };
  var putPolicy = new qiniu.rs.PutPolicy(options);
  const token = putPolicy.uploadToken(mac);
  const  id=options.returnBody;
  // const ids=JSON.stringify(id);
  // const id=ids.persistentId

  return{
    token,options,id
  }

}
const axios = require('axios');
// 获取持久化任务状态
async function getTaskStatus(persistentId) {
  const url = `http://api.qiniu.com/status/get/prefop?id=${persistentId}`;
  const result = await axios.get(url);
  return result.data;
}
// 查询七牛云转码进度并返回状态
async function getTaskStatus(persistentId) {
  const url = `http://api.qiniu.com/status/get/prefop?id=${persistentId}`;
  const result = await axios.get(url);
  return result.data;
}
// 查询七牛云转码进度并返回状态
async function checkTranscodeProgress(persistentId) {
  let status = '';
  let progress = '';
  while (status !== 0 && status !== 3 && status !== 4) {
    const taskStatus = await getTaskStatus(persistentId);
    status = taskStatus.code;
    progress = taskStatus.items[0].key;
    urls="http://rsr41x60z.hn-bkt.clouddn.com/"+progress;
    if (status === 1) {
      console.log('任务等待处理');
    } else if (status === 2) {
      console.log('任务正在处理中');
    } else if (status === 3) {
      throw new Error('任务处理失败');
    } else if (status === 4) {
      throw new Error('回调失败');
    }
    await new Promise(resolve => setTimeout(resolve, 1000)); // 每隔 1 秒轮询一次
  }
  return urls;
}

// 将上传视频和上传图片的函数封装成云函数
exports.main = async (event, context) => {
  const { functionName, key ,persistentId} = event;
  if (functionName === 'uploadShipin') {
    return await uploadShipin(key);
  }else if (functionName === 'checkTranscodeProgress') {
    return await checkTranscodeProgress(persistentId);
  } else {
    throw new Error('未知的函数名称');
  }
}

完成, 最后说一句 七牛云的文档是真垃圾

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值