1. 程式人生 > >微信小程式之圖片

微信小程式之圖片

微信小程式選擇圖片、預覽圖片、長按刪除圖片以及上傳圖片。

wxml部分:

<view class='imgs'>
    <block wx:for="{{tempFilePaths}}" wx:for-item="image">
      <image src="{{image}}" class='addImg' bindtap='previewImage' id="{{image}}" bindlongpress='deleteImage' data-index='{{index}}'></image>
    </block>
    <image src='../images/add_img.jpg' class='addImg' bindtap='chooseImage' hidden='{{addState}}'></image>
  </view>
  <view class='btn' bindtap='upload'>上傳</view>

js部分:

Page({
  data: {
    tempFilePaths: [],//圖片路徑
    addState: false,//新增圖片按鈕的狀態
  },

  /**
   * 生命週期函式--監聽頁面載入
   */
  onLoad: function (options) {

  },
  chooseImage: function () {//選擇圖片
    var that = this;
    wx.chooseImage({
      count: 9,//最多新增9張
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作為img標籤的src屬性顯示圖片
        const tempFilePaths = res.tempFilePaths;
        var State = false;
        if (res.tempFilePaths.length = 9) {//當選擇圖片等於9張時,則隱藏新增圖片按鈕
          State = true;
        } else {//當選擇圖片小於9張時,則顯示新增圖片按鈕
          State = false;
        }
        that.setData({
          tempFilePaths: res.tempFilePaths,
          addState: State
        })
      }
    });
  },
  previewImage: function (e) {//預覽圖片
    var that = this;
    wx.previewImage({
      current: e.currentTarget.id, // 當前顯示圖片的http連結
      urls: that.data.tempFilePaths // 需要預覽的圖片http連結列表
    })
  },
  deleteImage: function (e) {//刪除圖片
    var that = this;
    var images = that.data.tempFilePaths;
    var index = e.currentTarget.dataset.index;//獲取當前長按圖片下標
    wx.showModal({
      title: '提示',
      content: '確定要刪除此圖片嗎?',
      success: function (res) {
        if (res.confirm) {
          console.log('點選確定了');
          images.splice(index, 1);//通過splice方法刪除splice(index,1),刪除一個當前元素
          var State = false;//刪除圖片,圖片數量肯定小於9,So改變新增圖片按鈕的狀態,使之顯示
          that.setData({
              tempFilePaths: images,
              addState: State
        });
        } else if (res.cancel) {
          console.log('點選取消了');
          return false;
        }
       
      }
    })
  },
  upload: function () {//上傳圖片到伺服器
    var that = this;
    console.log("img", that.data.tempFilePaths);
    wx.uploadFile({
      url: 'xxx',//伺服器地址
      filePath: that.data.tempFilePaths,//圖片路徑
      name: 'file',
      formData: {
        'imgs': 'imgs'
      },
      success(res) {
        const data = res.data
      }
    });

  }

})