1.从微信里选择图片或文件上传
使用的vant的上传组件 原生用 wx.chooseMessageFile()
html
<!-- 从微信上面选择文件 --><van-uploader file-list="{{ file }}" bind:after-read="afterRead" max-count="{{3}}" deletable="{{ true }}" bind:delete="deleteAll" accept="all"><van-button custom-class="fup" square icon="plus" type="default"></van-button></van-uploader>
max-count 是限制上传图片数量 可以不设置该属性
js
// 从微信选择上传文件afterRead(e) {let that = thisconsole.log("上传的文件:", e.detail.file);wx.uploadFile({accept: "all",url: 'http://www.com/upload', // 仅为示例,非真实的接口地址filePath: e.detail.file.url,name: 'file',header: {'token': wx.getStorageSync("token"),// 请求需要token就带,不需要就删除},success(res) {console.log(res);let data = JSON.parse(res.data)data.data.name = e.detail.file.nameif (data.code == 1) {wx.showToast({icon: 'none',title: '上传成功!',duration: 2000})// 上传完成需要更新 fileListlet file = that.data.filefile.push(data.data)that.setData({file})console.log(that.data.file);} else {wx.showToast({icon: 'none',title: '上传失败!',duration: 2000})}},});},// 删除上传文件deleteAll(e) {console.log(e);let filearr = this.data.filefilearr.splice(e.detail.index, 1)this.setData({file: filearr})console.log(this.data.file);},
2.从相册选择图片上传
html
<!-- 从相册选择图片 --><view style="display: flex;justify-content: start;flex-wrap: wrap;margin-top: 20rpx;"><view wx:for="{{file}}" wx:key="{{index}}" class="img"><image src="{{item.url}}" mode="widthFix" /><view class="del" bindtap="deleteAll" data-index="{{index}}"><van-icon name="cross" /></view></view><van-button custom-class="fup" bindtap="pushimg" square icon="plus" type="default"></van-button></view>
js
// 删除上传文件deleteAll(e) {console.log(e);let filearr = this.data.filefilearr.splice(e.detail.index, 1)this.setData({file: filearr})console.log(this.data.file);},// 从相册选择图片pushimg() {let that = thiswx.chooseImage({ // 本地资源上传到服务器APIsuccess: function (e) {console.log(e);var tempFilePaths = e.tempFilePaths;wx.uploadFile({accept: "all",url: 'http://www.com/upload', // 指定服务器接口URLfilePath: tempFilePaths[0], // 本地文件路径,即选择文件返回的路径header: {'token': wx.getStorageSync("token"),// 请求需要token就带,不需要就删除},name: 'file', // 上传文件的key,后台要用到success: function (res) { //成功后的回调函数console.log(res);let data = JSON.parse(res.data)data.data.name = new Date()if (data.code == 1) {wx.showToast({icon: 'none',title: '上传成功!',duration: 2000})// 上传完成需要更新 fileListlet file = that.data.filefile.push(data.data)that.setData({file})console.log(that.data.file);} else {wx.showToast({icon: 'none',title: '上传失败!',duration: 2000})}}})}})},
less
.img {position: relative;width: 80px;margin-right: 15rpx;overflow: hidden;image {width: 100%;}.del {color: #ffffff;background-color: #000000;width: 40rpx;height: 40rpx;position: absolute;text-align: center;top: -13rpx;right: -13rpx;border-radius: 50%;z-index: 99;font-size: 20rpx;padding-top: 10rpx;padding-right: 10rpx;box-sizing: border-box;}
}