首页 > 编程 > JavaScript > 正文

微信小程序开发之从相册获取图片 使用相机拍照 本地图片上传

2019-11-19 16:48:06
字体:
来源:转载
供稿:网友

今天遇到微信小程序的用户头像设置功能,做笔记.

先上gif:

再上代码:

小demo,代码很简单.

1.index.wxml

<!--index.wxml--> <button style="margin:30rpx;" bindtap="chooseimage">获取图片</button> <image src="{{tempFilePaths }}" mode="aspecFill" style="width: 100%; height: 450rpx"/> 

2.index.js

//index.js //获取应用实例 var app = getApp() Page({  data: {   tempFilePaths: ''  },  onLoad: function () {  },  chooseimage: function () {   var _this = this;   wx.chooseImage({    count: 1, // 默认9    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有    success: function (res) {     // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片     _this.setData({      tempFilePaths:res.tempFilePaths     })    }   })  } }) 

API 说明:

这里说说sourcetype.默认是从相册获取和使用相机拍照,跟微信现在选择图片的界面一样,第一格是拍照,后面的是相册照片.

这里注意:返回的是图片在本地的路径.如果需要将图片上传到服务器,需要用到另一个API.

示例代码:

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    }   })  } }) 

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持武林网!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表