一、上傳會用到的一些東西:
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這兩天會整理出來,盡請期待...