先看效果:
图片预览:
代码如下:
wxml
<view class="container">
<button bindtap="chooseImageTap">上传图片</button>
<view class="uploader__files">
<block wx:for="{{picPaths}}" wx:key="*this">
<view class="uploader__file" bindtap="previewImage" id="{{item}}">
<image class="uploader__img" src="{{item}}" mode="aspectFill" />
</view>
</block>
</view>
</view>
wxss
/**index.wxss**/
.uploader__file {
float: left;
margin-right: 8px;
margin-bottom: 8px;
width: 96px;
height: 96px;
background: no-repeat 50%;
background-size: cover
}
.uploader__img {
display: block;
width: 100%;
height: 100%;
}
js
// 获取应用实例
const app = getApp()
Page({
data: {
picPaths: []
},
//添加上传图片
chooseImageTap: function () {
var self = this;
wx.showActionSheet({
itemList: ['从相册中选择', '拍照'], // 按钮的文字数组,数组长度最大为 6
itemColor: "#00000", // 按钮的文字颜色
success: function (res) { // 接口调用成功的回调函数
if (res.tapIndex == 0) {
self.chooseWxImage('album');
} else if (res.tapIndex == 1) {
self.chooseWxImage('camera');
}
}
})
},
// 图片本地路径
chooseWxImage: function (type) {
var self = this;
wx.chooseImage({
sizeType: ['original', 'compressed'], // 原图、压缩图
sourceType: [type], // 选择图片的来源
success: function (res) {
// 下段注释代码可以先进行本地上传并预览
// let picPaths = self.data.picPaths;
// picPaths.push(res.tempFilePaths[0]);
// self.setData({
// picPaths
// })
self.upImgs(res.tempFilePaths[0]) //调用上传方法
}
})
},
//上传服务器
upImgs: function (imgurl) {
var self = this;
wx.uploadFile({
url: '后端接口地址', //后端接口地址
filePath: imgurl,
name: 'file',
header: {
'content-type': 'multipart/form-data'
},
formData: null,
success: function (res) {
var data = JSON.parse(res.data); //接口返回网络路径
self.data.picPaths.push(data);
self.setData({
picPaths: self.data.picPaths
})
}
})
},
// 图片预览
previewImage: function(e){
let picPaths = this.data.picPaths;
wx.previewImage({
current: e.currentTarget.id, // 当前显示图片的http链接
urls: picPaths // 需要预览的图片http链接列表
})
},
onLoad() {
}
})
使用了wx.showActionSheet、wx.chooseImage、wx.previewImage三个方法,我们依次来看下:
wx.showActionSheet
wx.chooseImage
wx.previewImage
参考资料:
https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseImage.html
https://blog.csdn.net/weixin_42460570/article/details/81203206