考虑到日常项目中还是比较常用的,就整理了一下这案例,可以上传指定数量的图片或视频;
使用可以查看小程序文档:
选择图片: wx.chooseImage
选择视频:wx.chooseVideo
wxml:
<view class='the-tit'>上传图片:</view>
<view class='share-pics'>
<view class='slug-cons'>
<view class='pics'>
<view class='tp' wx:for="{{upImgArr}}" wx:key="item">
<image mode='aspectFill' class='img' src='{{item.path}}' data-presrc="{{item.path}}" bindtap='previewImg' />
<view class='delbtn' data-index="{{index}}" data-type="image" bindtap='delFile'>X</view>
</view>
</view>
<view class='btn' wx:if="{{upFilesBtn}}" data-type="image" bindtap='uploadFiles'></view>
</view>
</view>
js:
// pages/uploadPic/uploadPic.js
const app = getApp();
var util = require('../../utils/util.js');
var upFiles = require('../../utils/upFiles.js');
Page({
/**
* 页面的初始数据
*/
data: {
upImgArr: [], //存图片
upFilesBtn: true,
maxUploadLen: 9, //限制上传数量
},
// 选择图片或者视频
uploadFiles(e) {
var that = this,
type = e.currentTarget.dataset.type,
maxUploadLen = that.data.maxUploadLen;
if (type == 'image') {
upFiles.chooseImage(that, maxUploadLen);
} else if (type == 'video') {
upFiles.chooseVideo(that, maxUploadLen);
}
},
// 删除上传图片 或者视频
delFile(e) {
let that = this;
wx.showModal({
title: '温馨提示',
content: '您确认要删除这张图片吗?',
success(res) {
if (res.confirm) {
let delNum = e.currentTarget.dataset.index,
delType = e.currentTarget.dataset.type,
upImgArr = that.data.upImgArr,
upVideoArr = that.data.upVideoArr;
if (delType == 'image') {
upImgArr.splice(delNum, 1)
that.setData({
upImgArr: upImgArr
})
} else if (delType == 'video') {
upVideoArr.splice(delNum, 1)
that.setData({
upVideoArr: upVideoArr
})
}
let upFilesArr = upFiles.getPathArr(that);
if (upFilesArr.length < that.data.maxUploadLen) {
that.setData({
upFilesBtn: true,
})
}
} else if (res.cancel) {
console.log('用户点击取消')
}
}
})
},
// 预览图片
previewImg(e) {
let that = this,
imgsrc = e.currentTarget.dataset.presrc,
arr = that.data.upImgArr,
preArr = [];
arr.map(function (v, i) {
preArr.push(v.path)
})
//console.log(preArr)
wx.previewImage({
current: imgsrc,
urls: preArr
})
},
})
源码会持续更新到公众号,需要可以关注一下哦…