微信小程序---选择图片和调用微信拍照

1.实现点击头像按钮实现选择图片或者拍照,将图片重新设置成头像:

//index.js
//获取应用实例
var app = getApp()
Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    avatarUrl:null
  },
  //事件处理函数
  bindViewTap: function() {
   
   var that = this
    //  选择图片和拍照
    wx.chooseImage({
    count: 1, // 默认9
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
    success: function (res) {
      // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
      var tempFilePaths = res.tempFilePaths
      console.log("---"+tempFilePaths)
      that.setData({avatarUrl:tempFilePaths[0]})
    },
    fail: function (res) {
      console.log("fail...")
    },
    complete: function(res) {
      console.log("完成...")
    }
  })
  },
  onLoad: function () {
    console.log('onLoad')
    var that = this
    //调用应用实例的方法获取全局数据
    app.getUserInfo(function(userInfo){
      //更新数据
      that.setData({
        userInfo:userInfo
      })
    })
  }
})

2.文件的上传和下载:

wx.uploadFile(OBJECT)

将本地资源上传到开发者服务器。如页面通过 wx.chooseImage 等接口获取到一个本地资源的临时文件路径后,可通过此接口将本地资源上传到指定服务器。客户端发起一个 HTTPS POST 请求,其中 content-typemultipart/form-data

  1. tip: 最大并发限制是 10 个
  2. tip: 默认超时时间和最大超时时间都是 60s
wx.chooseImage({
  success: function(res) {
    var tempFilePaths = res.tempFilePaths
    wx.uploadFile({
      url: 'http://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
      filePath: tempFilePaths[0],
      name: 'file',
      formData:{
        'user': 'test'
      },
      success: function(res){
        var data = res.data
        //do something
      }
    })
  }
})

3.文件的下载:

wx.downloadFile(OBJECT)

下载文件资源到本地。客户端直接发起一个 HTTP GET 请求,返回文件的本地临时路径。

wx.downloadFile({
  url: 'http://example.com/audio/123', //仅为示例,并非真实的资源
  success: function(res) {
    wx.playVoice({
      filePath: res.tempFilePath
    })
  }
})
  1. tip: 最大并发限制是 10 个
  2. tip: 默认超时时间和最大超时时间都是 60s
  3. tip: 网络请求的 referer 是不可以设置的,格式固定为 https://servicewechat.com/{appid}/{version}/page-frame.html,其中 {appid} 为小程序的 appid,{version} 为小程序的版本号,版本号为 0 表示为开发版。
  4. tip: 6.5.3 以及之前版本的 iOS 微信客户端 header 设置无效

转载于:https://www.cnblogs.com/pengsi/p/6442794.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值