小程序从相册获取图片并上传以及使用相机拍照功能
2018-06-19|HiShop
导读:开发一个关于图片的小程序,会使用到小程序获取图片,图片上传以及获取相机权限的功能,那么要如何开发呢?...
开发一个关于图片的小程序,会使用到小程序获取图片,图片上传以及获取相机权限的功能,那么要如何开发呢?
1.index.wxml
- 1 <!--index.wxml-->
- 2 <button style="margin:30rpx;" bindtap="chooseimage">获取图片</button>
- 3 <image src="{{tempFilePaths }}" mode="aspecFill" style="width: 100%; height: 450rpx"/>
2.index.js
- 1 //index.js
- 2 //获取应用实例
- 3 var app = getApp()
- 4 Page({
- 5 data: {
- 6 tempFilePaths: ''
- 7 },
- 8 onLoad: function () {
- 9 },
- 10 chooseimage: function () {
- 11 var _this = this;
- 12 wx.chooseImage({
- 13 count: 1, // 默认9
- 14 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
- 15 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
- 16 success: function (res) {
- 17 // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
- 18 _this.setData({
- 19 tempFilePaths:res.tempFilePaths
- 20 })
- 21 }
- 22 })
- 23 }
- 24 })
这里说说sourcetype.默认是从相册获取和使用相机拍照,跟微信现在选择图片的界面一样,第一格是拍照,后面的是相册照片.
这里注意:返回的是图片在本地的路径.如果需要将图片上传到服务器,需要用到另一个API.
示例代码:
- 1 wx.chooseImage({
- 2 success: function(res) {
- 3 var tempFilePaths = res.tempFilePaths
- 4 wx.uploadFile({
- 5 url: 'http://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
- 6 filePath: tempFilePaths[0],
- 7 name: 'file',
- 8 formData:{
- 9 'user': 'test'
- 10 },
- 11 success: function(res){
- 12 var data = res.data
- 13 //do something
- 14 }
- 15 })
- 16 }
- 17 })