小程序OSS图片上传

时间:2023-03-09 03:59:22
小程序OSS图片上传

图片上传加水印问题,代码如下!

chooseImage: function (e) {
var that = this;
wx.chooseImage({
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
console.log(res)
let tempFilePaths = res.tempFilePaths;
let imgFile = res.tempFiles;
for (let i = 0; i < tempFilePaths.length;i++){
let n = tempFilePaths[i].lastIndexOf('.');
let type = tempFilePaths[i].substring(n);
wx.request({
url: 'https://www.********.com/api/plat/system/oss/signature?dir=wechatApp', //获取oss签名
success: function (res) {
console.log('签名', res.data.data)
if (res.data.status == 'SUCCESS') {
let post = res.data.data;
let foot1 = 'x-oss-process=image/resize,w_1080,h_1920,m_fill/watermark,type_d3F5LXplbmhlaQ,size_38,text_'
const aliyunFileKey = post.dir + that.guid() + type;
let showUrl = null;
wx.uploadFile({
url: post.host, //上传到OSS
filePath: tempFilePaths[i],
name: 'file',
formData: {
'key': aliyunFileKey,
'OSSAccessKeyId': post.accessKeyId,
'policy': post.policy,
'signature': post.signature,
'success_action_status': '200'
},
success: function (res) {
console.log("阿里云", res.statusCode)
if (res.statusCode == 200){
wx.showToast({
title: '上传成功',
icon:'success',
duration:1200
})
if (that.data.encodeWord) {
showUrl = post.host + '/' + aliyunFileKey + '?' + foot1 + that.data.encodeWord + that.data.urlFoot1;
} else {
showUrl = post.host + '/' + aliyunFileKey
}
let s = [showUrl]
that.setData({
files: that.data.files.concat(s)
});
}else{
wx.showToast({
title: '上传失败!',
icon: 'none',
duration: 1200
})
}
}
})
}
}
})
}
}
})

wx.uploader中的name字段必须为file. 我这里是需要回显预览图片的时候需要图片有水印效果,才会去更改data中的files,这样也能做到批量上传的效果。