商城系統(tǒng) 注冊(cè)

微信小程序調(diào)用內(nèi)置照相機(jī)實(shí)現(xiàn)拍照及圖片上傳

2020-09-27|HiShop
導(dǎo)讀: 一款小程序,很多時(shí)候需要調(diào)用內(nèi)置的照相機(jī),實(shí)現(xiàn)拍照并圖片上傳,那么要如何實(shí)現(xiàn)呢?...

  大家知道一款小程序,很多時(shí)候需要調(diào)用內(nèi)置的照相機(jī),實(shí)現(xiàn)拍照并圖片上傳,那么要如何實(shí)現(xiàn)呢?

  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
//獲取應(yīng)用實(shí)例
var app = getApp()

微信小程序調(diào)用內(nèi)置照相機(jī)實(shí)現(xiàn)拍照及圖片上傳

Page({
  data: {
    tempFilePaths: ''
  },
  onLoad: function () {
  },
  chooseimage: function () {
    var _this = this;
    wx.chooseImage({
      count: 1, // 默認(rèn)9
      sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認(rèn)二者都有
      sourceType: ['album', 'camera'], // 可以指定來源是相冊(cè)還是相機(jī),默認(rèn)二者都有
      success: function (res) {
        // 返回選定照片的本地文件路徑列表,tempFilePath可以作為img標(biāo)簽的src屬性顯示圖片
        _this.setData({
          tempFilePaths:res.tempFilePaths
        })
      }
    })
  }
})

  API 說明:

微信小程序調(diào)用內(nèi)置照相機(jī)實(shí)現(xiàn)拍照及圖片上傳

  這里說說sourcetype.默認(rèn)是從相冊(cè)獲取和使用相機(jī)拍照,跟微信現(xiàn)在選擇圖片的界面一樣,第一格是拍照,后面的是相冊(cè)照片.

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

  示例代碼:
 

wx.chooseImage({
  success: function(res) {
    var tempFilePaths = res.tempFilePaths
    wx.uploadFile({
      url: 'http://example.weixin.qq.com/upload', //僅為示例,非真實(shí)的接口地址
      filePath: tempFilePaths[0],
      name: 'file',
      formData:{
        'user': 'test'
      },
      success: function(res){
        var data = res.data
        //do something
      }
    })
  }
})

HiShop小程序工具提供多類型商城/門店小程序制作,可視化編輯 1秒生成5步上線。通過拖拽、拼接模塊布局小程序商城頁面,所看即所得,只需要美工就能做出精美商城。

更多小程序開發(fā)案例,盡在:http://descansotropical.com/xiaocx/kaifa.html


電話咨詢 預(yù)約演示 0元開店