php上传到腾讯cos,【小程序】--- 图片上传到COS(腾讯云)

以下为封装的js文件,上传时引入该文件,调用uploadFile方法传入图片临时地址,callback中接收上传后的网络地址;

(js的sdk的使用方式基本和小程序的差不多,不过上传后的访问地址不是callback返回的,而是需要自己根据前缀和图片名手动拼接)

const app = getApp();

const { $req } = require('./request.js'); // $req方法为对微信request方法的封装,这里就不过多赘述了

const COS = require('../static/js/cos-wx-sdk-v5-min.js'); // 引入sdk

const Bucket = 'xxx-11111111'; // 这里填你存储桶名称

const Region = 'ap-beijing'; // 填你的地域名称

const cos = new COS({

getAuthorization: function (options, callback) {

// 异步获取签名

$req({

url: 'xxx', // 后端签名接口

method: 'POST',

success(result) {

console.log(result);

let data = result.data.data;

let credentials = data.credentials;

callback({

TmpSecretId: credentials.tmpSecretId,

TmpSecretKey: credentials.tmpSecretKey,

XCosSecurityToken: credentials.sessionToken,

ExpiredTime: data.expiredTime, // SDK 在 ExpiredTime 时间前,不会再次调用 getAuthorization

});

}

})

}

});

// 上传文件

const uploadFile = (filePath, callback) => {

let filename = filePath.substr(filePath.lastIndexOf('/') + 1);

cos.postObject({

Bucket: Bucket,

Region: Region,

Key: filename,

FilePath: filePath,

onProgress: info => {

console.log(JSON.stringify(info));

}

}, (err, data) => {

if (err === null) {

callback(data);

} else {

wx.hideLoading();

wx.showToast({

title: '上传失败',

icon: 'none'

})

}

});

}

module.exports = {

uploadFile,

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值