在微信小程序中实现多图片上传功能,可以让用户轻松记录生活中的美好瞬间。以下是一步一步的操作指南,帮助你实现这一功能。
一、准备工作
在开始之前,确保你已经:
- 注册并登录微信公众平台。
- 创建小程序并获取AppID。
- 安装并配置开发环境。
二、创建页面
- 新建页面:在开发者工具中,新建一个页面,例如命名为
upload-image。 - 设置页面结构:在
upload-image.wxml文件中,添加一个用于展示图片的容器和上传按钮。
<view class="container">
<view class="image-container">
<block wx:for="{{images}}" wx:key="index">
<image src="{{item}}" class="image-item" />
</block>
</view>
<button bindtap="uploadImages">上传图片</button>
</view>
三、设置样式
在upload-image.wxss文件中,添加以下样式:
.container {
padding: 20rpx;
}
.image-container {
display: flex;
flex-wrap: wrap;
margin-bottom: 20rpx;
}
.image-item {
width: 150rpx;
height: 150rpx;
margin-right: 10rpx;
margin-bottom: 10rpx;
}
四、编写逻辑
在upload-image.js文件中,编写以下代码:
Page({
data: {
images: []
},
uploadImages: function() {
const that = this;
wx.chooseImage({
count: 9, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths = res.tempFilePaths;
that.setData({
images: that.data.images.concat(tempFilePaths)
});
}
});
}
});
五、上传图片到服务器
- 后端设置:在服务器上创建一个接口,用于接收上传的图片。
- 调用接口:在
uploadImages函数中,调用服务器接口,上传图片。
uploadImages: function() {
const that = this;
wx.chooseImage({
count: 9,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
const tempFilePaths = res.tempFilePaths;
wx.uploadFile({
url: 'https://your-server.com/upload', // 你的服务器接口地址
filePath: tempFilePaths[0],
name: 'file',
formData: {
'user': 'test'
},
success: function (res) {
const data = JSON.parse(res.data);
if (data.success) {
wx.showToast({
title: '上传成功',
icon: 'success',
duration: 2000
});
} else {
wx.showToast({
title: '上传失败',
icon: 'none',
duration: 2000
});
}
},
fail: function (err) {
wx.showToast({
title: '上传失败',
icon: 'none',
duration: 2000
});
}
});
}
});
}
六、测试与优化
- 测试:在手机上运行小程序,测试上传图片功能是否正常。
- 优化:根据测试结果,优化代码和用户体验。
通过以上步骤,你就可以在微信小程序中实现多图片上传功能了。这样,用户就可以轻松记录生活中的美好瞬间,分享给亲朋好友。
