上传多张图片
<view class="big-logos">
<view class='big-logos_img'>
<button bindtap="upimg" class="iconfont icon-tianjia1 unloadIcon"></button>
</view>
<block wx:for="{{img_arr}}" wx:key="{{index}}">
<view class='logoinfo'>
<image src='{{item}}'></image>
</view>
</block>
</view>
data:{
img_arr: []
}
upimg: function () { //选择图片
var that = this;
if (this.data.img_arr.length < 3) {
wx.chooseImage({
sizeType: ['original', 'compressed'],
success: function (res) {
that.setData({
img_arr: that.data.img_arr.concat(res.tempFilePaths)
})
}
})
} else {
wx.showToast({
title: '最多上传三张图片',
icon: 'loading',
duration: 3000
});
}
}
unload:function(){ //上传图片 需要在页面上定义一个事件去触发上传图片,上面的事件只是去选择图片并没有实际的上传到服务器
var that = this
for (var i = 0; i < this.data.img_arr.length; i++) {
wx.uploadFile({
url: getApp().globalData.url + "/upload",
filePath: that.data.img_arr[i],
name: 'pic',//这是后台主要的参数key值
header: {
"Content-Type": "multipart/form-data"
},
formData: {
Authorization: getApp().globalData.token
},
success: function (res) {
}
})
}
}
上传一张图片
<view class="head_portrait">
<image bindtap="uploadPhoto" class="head_pic" src="{{src}}"></image>
<view class="head_txt">宝贝头像</view>
</view>
data:{
src : ''
}
uploadPhoto() {//选择图片
var that = this;
wx.chooseImage({
count: 1, // 默认9
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;
upload(that, tempFilePaths);
}
})
}
function upload(page, path) {//放在page()外面就好了
wx.showToast({
icon: "loading",
title: "正在上传"
}),
wx.uploadFile({
url: getApp().globalData.url +"/upload",//把url换了
filePath: path[0],
name: 'pic',//这个是后台主要的参数key值
header: {
"Content-Type": "multipart/form-data"
},
formData: {
//和服务器约定的token, 一般也可以放在header中
Authorization: getApp().globalData.token
},
success: function (res) {
console.log(res);
if (res.statusCode != 200) {
wx.showModal({
title: '提示',
content: '上传失败',
showCancel: false
})
return;
}
page.setData({ //上传成功修改显示头像
src: path[0]
})
},
fail: function (e) {
console.log(e);
wx.showModal({
title: '提示',
content: '上传失败',
showCancel: false
})
},
complete: function () {
wx.hideToast(); //隐藏Toast
}
})
}
预览图片 wx:previewImage
<image src='/images/step-images.jpg' bindtap='clickImg' data-srcimg="服务器的路径"></image>
clickImg: function (e) {//预览图片
console.log(e);
var current = e.target.dataset.srcimg;
wx.previewImage({
current: current, // 当前显示图片的http链接
urls: [] // 需要预览的图片http链接列表
})
}
完美。