一:上传图片
js
const app = getApp();Page({ /** * 页面的初始数据 */ data: { pic: '', }, //上传单张图片 addPic(e) { var that = this; wx.chooseImage({ count: 1, // 默认9 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], success: res = { // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 var tempFilePaths = res.tempFilePaths; upload(that, tempFilePaths) //头像 that.setData({ textPic: tempFilePaths }) }, fail: res = { console.log("error:" + res) } }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function(options) { },})//通用的上传图片方法//page 等价于 this.data.参数名中的 this//path 为图片临时路径function upload(page, path) { wx.showToast({ icon: "loading", title: "正在上传" }), wx.uploadFile({ url: "服务器上传地址", filePath: path[0], name: 'file',、、服务器接收的文件的名字 header: { "Content-Type": "multipart/form-data", "Authorization": wx.getStorageSync('Authorization'), }, formData: { //服务器需要的额外参数 'type': 'base' }, success: function(res) { let data = res.data; let pic = data.data.path console.log(pic) if (res.statusCode != 200) { wx.showModal({ title: '提示', content: '上传失败', showCancel: false }) return; } //将图片存起来 page.setData({ pic: pic }) }, fail: function(e) { console.log(e); wx.showModal({ title: '提示', content: '上传失败', showCancel: false }) }, complete: function() { wx.hideToast(); //隐藏Toast } })}在 wxml 中对相应的上传btn进行绑定 addPic 事件即可。
二:查看大图
js
//预览单个图片 previewMoreImage(e) { let src = e.currentTarget.dataset.src; let urlarr = []; urlarr.push(src) wx.previewImage({ current: src, urls: urlarr }) },wxml
//data-src为预览图路径image src='http://os01.mddyg.com/picture/base/1530684511155_stfSXU' data-src='http://os01.mddyg.com/picture/base/1530684511155_stfSXU' mode="widthFix" bindtap='previewMoreImage' class="service_img"/image













