微信小程序 · 图片上传

小程序 · 图片上传

在小程序端实现图片上传,需要调用小程序的图片选择接口(chooseImage)和本地资源上传接口(uploadFile)。

1. wx.chooseImage()

  • 从本地相册选择图片或使用相机拍照。

参数:
在这里插入图片描述

实例:

wx.chooseImage({
  count: 1,//可选图片数量
  sizeType: ['original'],//original	原图	compressed	压缩图
  sourceType: ['album', 'camera'],//支持选取图片album	从相册选图	camera	使用相机
  success (res) {
    // tempFilePath可以作为img标签的src属性显示图片
    const tempFilePaths = res.tempFilePaths[0]
    this.setData({
        ["userInfo.url"] : tempFilePaths
    })
  }
})

2. wx.unloadFile()

  • 将本地资源上传到服务器。客户端发起一个 HTTPS POST 请求,其中 content-typemultipart/form-data

参数:

在这里插入图片描述

实例:

wx.uploadFile({
    // 后台请求地址
    url: 'https://192.168.1.1:8080/upload',
    // 文件本地路径
    filePath: this.data.userInfo.url,
    // 后台获取我们图片的key
    name: 'file',
    // 额外的参数
    formData: {
        // 一般传递token
        'user': 'test'
    },
    success(res) {
        console.log(res)
    },
    fail: function (err) {
        console.log(err)
    }
})

3. 实现

// 图片上传 API

const upload = () => {
  return new Promise((resolve, reject) => {
    wx.chooseImage({
      count: 1,//可选图片数量
      sizeType: ['original'],//original	原图	compressed	压缩图
      sourceType: ['album', 'camera'],//支持选取图片album	从相册选图	camera	使用相机
      success(res) {
        // 获取图片路径
        const tempFilePaths = res.tempFilePaths
        resolve(res)
        wx.uploadFile({
          // 后台请求地址
          url: 'https://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
          // 文件本地路径
          filePath: tempFilePaths[0],
          // 后台获取我们图片的key
          name: 'file',
          // 额外的参数
          formData: {
            // 一般传递token
            'user': 'test'
          },
          success(res) {
            resolve(res)
          },
          fail: function (err) {
            reject(err)
          }
        })
      }
    })
  })
}


export default upload
//接口调用
import upload from '../../api/upload'//引入
...
uploadImg() {
    // 上传图片
    upload().then(res => {
        console.log(res)
        this.setData({
            ["userList[0].url"]: res.tempFilePaths[0],
            imgUrl: res.tempFilePaths[0],
            isUpload: false,
        })
    }).catch(err => {
        console.log(err)
    })
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值