图片选择与预览
调用wx.chooseImage
接口
使用该API从相册或相机获取图片,支持多选(默认最多9张)及压缩格式:
wx.chooseImage({ count: 3, // 最大选择数 sizeType: ['original', 'compressed'], // 原图或压缩图 sourceType: ['album', 'camera'], // 来源类型 success(res) { const tempFilePaths = res.tempFilePaths; // 获取临时路径 this.setData({ imgs: tempFilePaths }); // 存储至页面数据 } });
预览功能
通过wx.previewImage
实现单张或多张图片预览:
wx.previewImage({ current: tempFilePaths[0], // 当前显示图片 urls: tempFilePaths // 所有图片路径 });
图片上传至服务器
使用wx.uploadFile
接口
将本地文件上传至指定服务器,需注意请求头与表单数据配置:
wx.uploadFile({ url: 'https://your-server.com/upload', // 服务端接口 filePath: tempFilePaths[0], // 本地文件路径 name: 'file', // 后端接收字段名 formData: { user: 'test' }, // 附加参数 header: { 'Content-Type': 'multipart/form-data' }, // 请求头 success(res) { console.log('上传成功:', JSON.parse(res.data)); }, fail(err) { wx.showToast({ title: '上传失败', icon: 'none' }); } });
图片删除与状态管理
删除已选图片
通过splice
方法操作图片数组实现动态删除:
deleteImg(e) { const index = e.currentTarget.dataset.index; const imgs = this.data.imgs; imgs.splice(index, 1); this.setData({ imgs }); }