小程序模板:专业的小程序模板与静态模板分享平台
小程序
教程
搜索
当前位置 : 首页> 小程序教程> 微信小程序实现上传图片功能

微信小程序实现上传图片功能

一、核心实现步骤

  1. 图片选择与预览

    • 调用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 });
}

联系客服 意见反馈

签到成功!

已连续签到1天,签到3天将获得积分VIP1天

知道了