小程序前端直传阿里云oss的一些记录

一、上传会用到的一些东西:

1.wx.chooseImage;
2.wx.uploadFile;
3.获取上传需要的签名(signature)和加密策略(policy)和上传url(host)的接口;

二、步骤拆解:

1.通过接口获取签名等信息;
2.选择图片得到filePath;
3.上传图片得到oss图片路径并渲染;

三、代码实现:

1.请求接口得到如下policy对象:
ossPolicy:{
            OSSAccessKeyId: "LTAIEGwazoZUp6GV",
            accessid: "LTAIEGwazoZUp6GV",
            dir: "",
            expire: 1559634215,
            host: "http://dhb-business-card.oss-cn-hangzhou.aliyuncs.com",
            policy: "eyJleHBpcmF0aW9uIjoiMjAxOS0wNi0wNFQxNTo0MzozNVoiLCJjb25kaXRpb25zIjpbWyJjb250ZW50LWxlbmd0aC1yYW5nZSIsMCwyMDk3MTUyMDBdLFsic3RhcnRzLXdpdGgiLCIka2V5IiwiIl1dfQ==",
            signature: "2n+ATkFZmsuBWrXcfi7hHH9/c+Y="
        }

 2.选择图片:

//选择图片
    publishGallery() {
        var imageArray = [];// 多图临时路径数组
        wx.chooseImage({
            count: 9, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
            success: function (res) {
                let filePath = res.tempFilePaths;
                this.uploadImg(filePath)
            }
        })
    },

 3.上传图片

// 上传图片
uploadImg(filePath){
let _this = this;

_this.setData({
uploadPercent: true
})

let {
host,
OSSAccessKeyId,
policy,
signature
} = this.ossPolicy;

let imgList = [];
filePath.map((item) => {
wx.uploadFile({
url: host,
filePath: item,
name: 'file',
formData: {
name: item,
key: 'bbs/${filename}',
success_action_status: '200',
OSSAccessKeyId,
policy,
signature
},
success: res => {
if (res.statusCode === 200) {
_this.setData({
uploadPercent: false
});
const fileName = item.split('http://tmp/')[1];
imgList.push(`${host}/bbs/${fileName}`);
_this.setData({
img_l: imgList
});
}
},
fail: res => {
console.log(res)
}
})
});
},

 注意事项:

1.上传中拼装的formData中的key为与后端约定的文件名,一般需要进行时间戳加密或者md5加密;

2.后面渲染图片时,imgList的拼装名一定要合key值对应,不然会出现问题;

3.如若需要对图片大小之类的进行一些限制,在chooseImage的success回调里对res.tempFiles进行相关处理;

-----vue和react的前端直传oss这两天会整理出来,尽请期待...




原文地址:https://www.cnblogs.com/vonson/p/11152456.html