美文网首页
【小程序】--- 图片上传到COS(腾讯云)

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

作者: 愫幕 | 来源:发表于2019-05-15 21:20 被阅读0次

    以下为封装的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,
    }
    

    相关文章

      网友评论

          本文标题:【小程序】--- 图片上传到COS(腾讯云)

          本文链接:https://www.haomeiwen.com/subject/cxnfoqtx.html