- 效果图添加图片前:
添加上图片后:
wxml内容:
<view class="" hover-class="hover-class" catchtap="openChooseImage" style="height: 368rpx;background: #E6EEFE url({{ imgpath ? imgpath + '/bgIcon/addPhoto.png' : '' }}) no-repeat center;background-size: 88rpx 88rpx;">
<image wx:if="{{imagePath}}" src="{{ imagePath }}" style="max-width: 100%;max-height: 100%;"></image>
</view>
- js内容:
调用 wx.chooseImage 方法,从本地相册选择图片或使用相机拍照 。wx.chooseImage:官网地址
// 打开相册-点击事件
openChooseImage: function() {
let that = this;
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success(res) {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths = res.tempFilePaths
that.setData({
imagePath: tempFilePaths
})
}
})
}
调用 wx.uploadFile
将图片保存到服务器。 wx.uploadFile:官网地址
wx.uploadFile({
url: app.severpath+"/api/serveUpdate",
filePath: this.data.imagePath[0],
name: "photoFile",
formData: params,
// 请求成功
success: function (res) {
res.data = JSON.parse(res.data);
//隐藏加载提示
wx.hideLoading();
if(res.statusCode == 200){
if(res.data.code == 200){
wx.showModal({
title: '提示',
showCancel: false,
content: '添加成功!'
});
// 清空表单数据
that.clearData();
}else{
// 提示错误信息
wx.showModal({
title: '提示',
content: '添加成功!',
showCancel: false
});
}
}else{
// 提示错误信息
wx.showModal({
title: '提示',
showCancel: false,
content: '添加成功!'
});
}
},
// 请求失败
fail: function(err){
wx.hideLoading();//隐藏加载提示
// 提示错误信息
wx.showModal({
title: '提示',
showCancel: false,
content: '添加成功!'
});
}
})