(乾貨)微信小程序之上傳圖片和圖片預覽

這幾天一直負責作微信小程序這一塊,也能夠說是邊作邊學習吧,把本身作的微信小程序的一些功能分享出來,與你們探討一下,相互學習相互進步。javascript

先看下效果圖前端

只寫了一下效果樣式的話但願你們不要太在乎,下面馬路殺手要開車了。java

1.wxml排版和佈局

  這個排版很是簡單就是一個按鈕button加個圖片image標籤而已,這個相信有點基礎的人都能理解,直接放代碼:git

<view class="container">
  <view class="userinfo">
    <button bindtap="upload"> 上傳圖片 </button>
  </view>
  <block wx:for="{{tempFilePaths}}" wx:key="{{index}}">
    <image src="{{item }}" bindtap="listenerButtonPreviewImage" data-index="{{index}}" style="width: 100%;"/>
  </block>
</view>

2.重要的js

  首先定義一個點擊按鈕上傳圖片的一個事件,這裏會用到微信圖片API中的wx.chooseImagegithub

  這個API會有6個參數分別是:小程序

 

參數 類型 必填 說明
count Number 最多能夠選擇的圖片張數,默認9
sizeType StringArray original 原圖,compressed 壓縮圖,默認兩者都有
sourceType StringArray album 從相冊選圖,camera 使用相機,默認兩者都有
success Function 成功則返回圖片的本地文件路徑列表 tempFilePaths
fail Function 接口調用失敗的回調函數
complete Function 接口調用結束的回調函數(調用成功、失敗都會執行)

 

好了該介紹的都介紹了,下面來看下代碼:微信小程序

upload: function () {
    let that = this;
    wx.chooseImage({
      count: 9, // 默認9
      sizeType: ['original', 'compressed'], // 能夠指定是原圖仍是壓縮圖,默認兩者都有
      sourceType: ['album', 'camera'], // 能夠指定來源是相冊仍是相機,默認兩者都有
      success: res => {
        wx.showToast({
          title: '正在上傳...',
          icon: 'loading',
          mask: true,
          duration: 1000
        })  
        // 返回選定照片的本地文件路徑列表,tempFilePath能夠做爲img標籤的src屬性顯示圖片
        let tempFilePaths = res.tempFilePaths;
        that.setData({
          tempFilePaths: tempFilePaths
        })
  
      }
    })
  },

不要以爲這樣就萬事大吉了,如今僅僅是在前端顯示,你還要上傳到服務器,上傳的話就會用到另外一個API了wx.uploadFile服務器

這個API會有8個參數微信

參數 類型 必填 說明
url String 開發者服務器 url
filePath String 要上傳文件資源的路徑
name String 文件對應的 key , 開發者在服務器端經過這個 key 能夠獲取到文件二進制內容
header Object HTTP 請求 Header, header 中不能設置 Referer
formData Object HTTP 請求中其餘額外的 form data
success Function 接口調用成功的回調函數
fail Function 接口調用失敗的回調函數
complete Function 接口調用結束的回調函數(調用成功、失敗都會執行)

下面來看下代碼是什麼樣的:ide

upload: function () {
    let that = this;
    wx.chooseImage({
      count: 9, // 默認9
      sizeType: ['original', 'compressed'], // 能夠指定是原圖仍是壓縮圖,默認兩者都有
      sourceType: ['album', 'camera'], // 能夠指定來源是相冊仍是相機,默認兩者都有
      success: res => {
        wx.showToast({
          title: '正在上傳...',
          icon: 'loading',
          mask: true,
          duration: 1000
        })  
        // 返回選定照片的本地文件路徑列表,tempFilePath能夠做爲img標籤的src屬性顯示圖片
        let tempFilePaths = res.tempFilePaths;

        that.setData({
          tempFilePaths: tempFilePaths
        })
        /**
         * 上傳完成後把文件上傳到服務器
         */
        var count = 0;
        for (var i = 0, h = tempFilePaths.length; i < h; i++) {
          //上傳文件
        /*  wx.uploadFile({
            url: HOST + '地址路徑',
            filePath: tempFilePaths[i],
            name: 'uploadfile_ant',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success: function (res) {
              count++;
              //若是是最後一張,則隱藏等待中  
              if (count == tempFilePaths.length) {
                wx.hideToast();
              }
            },
            fail: function (res) {
              wx.hideToast();
              wx.showModal({
                title: '錯誤提示',
                content: '上傳圖片失敗',
                showCancel: false,
                success: function (res) { }
              })
            }
          });*/
        }  
        
      }
    })
  },

有的人會有疑問爲何會定義一個count爲0呢,就是由於須要判斷是否是最後一張圖片若是是就不須要顯示加載中了。

好了,上傳圖片基本上說完了接着看預覽圖片,預覽圖片的話也要用到一個微信的API是wx.previewImage

這個API有五個參數

current String 當前顯示圖片的連接,不填則默認爲 urls 的第一張
urls StringArray 須要預覽的圖片連接列表
success Function 接口調用成功的回調函數
fail Function 接口調用失敗的回調函數
complete Function 接口調用結束的回調函數(調用成功、失敗都會執行)

定義預覽圖片方法,點擊圖片的時候執行:

listenerButtonPreviewImage: function (e) {
    let index = e.target.dataset.index;//預覽圖片的編號
    let that = this;
    wx.previewImage({
      current: that.data.tempFilePaths[index],//預覽圖片連接
      urls: that.data.tempFilePaths,//圖片預覽list列表
      success: function (res) {
        //console.log(res);
      },
      fail: function () {
        //console.log('fail')
      }
    })
  },

這個時候纔算是大工告成,若是想看完整代碼能夠去我github上去看https://github.com/Mr-MengBo/upload-pic

你們有問題的話能夠提出來,咱們一塊兒解決,一塊兒進步,但願本文章對你們有幫助,謝謝

相關文章
相關標籤/搜索