[轉]微信小程序開發之從相冊獲取圖片 使用相機拍照 本地圖片上傳


本文轉自:http://blog.csdn.net/qq_31383345/article/details/53014610

今天遇到微信小程序的用戶頭像設置功能,做筆記.

先上gif:

再上代碼:

小demo,代碼很簡單.

1.index.wxml

 

[html]  view plain  copy
 
  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

 

[javascript]  view plain  copy
 
  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. })  

 

 

API 說明:


這里說說sourcetype.默認是從相冊獲取和使用相機拍照,跟微信現在選擇圖片的界面一樣,第一格是拍照,后面的是相冊照片.

這里注意:返回的是圖片在本地的路徑.如果需要將圖片上傳到服務器,需要用到另一個API.

示例代碼:

 

[javascript]  view plain  copy
 
  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. })  

 

 

我的博客:http://blog.csdn.net/qq_31383345

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM