1)使用场景:
weui里面有很多组件,其中一个是上传组件,如果你有上传图片的需求,使用mp-uploader开发效率也快很多,也能减少代码包体。
2)效果图:
3)实现流程:
- app.json配置useExtendedLib的weui功能
- app.js初始化云开发(需保证已开放云开发功能)
- 页面代码如下
// index.json
{
"navigationBarTitleText": "上传图片",
"usingComponents": {
"mp-uploader": "weui-miniprogram/uploader/uploader"
}
}
// index.wxml
<mp-uploader title="投诉凭证" max-count="3" files="{{files}}" upload="{{uploadFn}}" binddelete="uploadDelect"
bindsuccess="uploadSuccess">
</mp-uploader>
// index.js
let that = this;
Page({
data: {
files: [],
async uploadFn(e) {
let urls = [];
for (let i = 0; i < e.tempFilePaths.length; i++) {
urls.push(await that.upLoadImg(e.tempFilePaths[i]));
}
return { urls };
},
},
onLoad() {
that = this;
},
uploadDelect(e) {
let files = this.data.files;
files.splice(e.detail.index, 1);
this.setData({ files });
},
uploadSuccess(e) {
let files = this.data.files;
e.detail.urls.forEach((url) => {
files.push({
url,
});
});
this.setData({
files,
});
},
async upLoadImg(filePath) {
let cloudPath = `mini/${new Date().getTime()}.png`;
let { fileID } = await wx.cloud.uploadFile({
cloudPath,
filePath,
});
return this.fileIDToHttps(fileID);
},
// 图片地址: fileID 转 https
fileIDToHttps(url) {
let res = url;
if (url.indexOf("cloud://") === 0) {
const first = url.indexOf(".");
const end = url.indexOf("/", first);
res =
"https://" +
url.slice(first + 1, end) +
".tcb.qcloud.la/" +
url.slice(end + 1, url.length);
}
return res;
},
});
4)注意点:
注意upload上传函数是在data里的函数,该函数的this指向为上传图片对象,非页面实例。
5)相关联文章:
还有一个问题 别人访问我的这个图片,能不能通过我的这个url,恶意操作,会不会产生安全问题
https://7465-test-6gz4v8cq0b874ea2-1311992300.tcb.qcloud.la/mini/1654699803146.png
大佬 使用你这样的,但是图片url太长了 有没有办法缩短url的长度