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


這幾天一直負責做微信小程序這一塊,也可以說是邊做邊學習吧,把自己做的微信小程序的一些功能分享出來,與大家探討一下,相互學習相互進步。

先看下效果圖

只寫了一下效果樣式的話希望大家不要太在意,下面馬路殺手要開車了。

1.wxml排版和布局

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

<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.chooseImage

  這個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 接口調用結束的回調函數(調用成功、失敗都會執行)

下面來看下代碼是什么樣的:

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

大家有問題的話可以提出來,我們一起解決,一起進步,希望本文章對大家有幫助,謝謝


免責聲明!

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



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