使用uniapp开发微信小程序通过STS直传阿里云OSS

看了看阿里云官方文档后简单封装了一下,方便以后使用

aliOssSts.js

/**
 * 微信小程序通过STS直传阿里云OSS
 *(uniapp版上传,小程序原生需要将uni.XXX替换为wx.XXX)
 * 
 * @param {filePath} 图片临时地址
 * @param {option|Object} OSS和STS配置
 * @param {savePath} oss中的文件目录
 * @param {AccessKeySecret} 服务端返回的STS中的AccessKeySecret
 * @param {SecurityToken} 服务端返回的STS中的SecurityToken
 * @param {AccessKeyId} 服务端返回的STS中的AccessKeyId
 * @param {bucket} 存储桶
 * @param {area} 地区
 * @return {string|boolean} 成功返回文件地址,失败返回false
 */

import crypto from 'crypto-js';
import {
    Base64
} from 'js-base64/base64.js';

function upload(filePath, option = {
    savePath,
    AccessKeySecret,
    SecurityToken,
    AccessKeyId,
    bucket,
    area
}, callBack = () => {}) {
    let fileType = filePath.split(".").pop();
    let filename = option.savePath + "/" + createFileName(32) + "." + fileType;


    const date = new Date();
    date.setHours(date.getHours() + 1);
    const policyText = {
        expiration: date.toISOString(), // 设置policy过期时间。
        conditions: [
            ["content-length-range", 0, 1024 * 1024 * 1024],
        ],
    };
    const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
    const signature = computeSignature(option.AccessKeySecret, policy)
    const formData = {
        OSSAccessKeyId: option.AccessKeyId,
        signature,
        policy,
        'x-oss-security-token': option.SecurityToken,
        key: filename,
        success_action_status: 200
    }

    uni.uploadFile({
        url: "https://" + option.bucket +
            "." + option.area + ".aliyuncs.com",
        filePath: filePath,
        name: "file",
        formData: formData,
        success: (res) => {
            let ossFileName = false;
            if (res.statusCode === 200) {
                console.log('上传成功');
                ossFileName = "https://" + option.bucket +
                    "." + option.area + ".aliyuncs.com/" +
                    filename;
            }
            callBack(ossFileName);
        },
        fail: err => {
            console.log(err);
            callBack(false);
        }
    })
}




// 签名
function computeSignature(accessKeySecret, canonicalString) {
    return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
}

// 生成随机文件名
function createFileName(length) {
    const data = [
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
        "a",
        "b",
        "c",
        "d",
        "e",
        "f",
        "g",
        "h",
        "i",
        "j",
        "k",
        "l",
        "m",
        "n",
        "o",
        "p",
        "q",
        "r",
        "s",
        "t",
        "u",
        "v",
        "w",
        "x",
        "y",
        "z",
    ];
    let nums = "";
    for (let i = 0; i < length; i++) {
        const r = parseInt(Math.random() * 61, 10);
        nums += data[r];
    }
    return nums;
}




export default {
    upload
}

使用callback的方式获取上传结果

<script>
import AliOss from "@/存放路径/aliOssSts.js";
export default {
    data() {
        return {
            // OSS STS数据
            ossData: [],
        };
    },
    onLoad() {
        // 向后端请求STS信息
        this.getSts();
    },
    methods: {
        getSts() {
            let _this = this;
            this.request.get(this.api.sts).then((res) => {
                _this.ossData = res;
            });
        },
        chooseImage() {
            let _this = this;
            uni.chooseImage({
                count: 1,
                sizeType: ["compressed", "camera"],
                sourceType: ["album"],
                success: function (res) {
                    if (res.errMsg == "chooseImage:ok") {
                        let filePath = res.tempFiles[0].path;
                        let option = {
                            savePath: "image",
                            AccessKeySecret: _this.ossData.AccessKeySecret,
                            SecurityToken: _this.ossData.SecurityToken,
                            AccessKeyId: _this.ossData.AccessKeyId,
                            bucket: _this.ossData.bucket,
                            area: "oss-cn-beijing",
                        };
                        AliOss.upload(filePath, option, function (res) {
                            if (res) {
                                console.log(res);
                            } else {
                                _this.Fun.tip("图片上传失败,请稍后重试");
                            }
                        });
                    } else {
                        _this.Fun.tip("图片选择失败");
                    }
                },
            });
        },
    },
};
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值