1. 程式人生 > >小程式之圖片的上傳、刪除和預覽和視訊的上傳和刪除

小程式之圖片的上傳、刪除和預覽和視訊的上傳和刪除

最近在做一個小程式,帖子中用到了一個關於文字、圖片和視訊的一些操作。

最終的樣式

原始樣式 上傳圖片 上傳視訊
在這裡插入圖片描述 在這裡插入圖片描述 在這裡插入圖片描述

這個可以實現輸入文字的統計和限制,圖片的上傳、預覽和刪除,視訊的上傳和刪除功能。

如何實現上面的那些樣式呢?

大家可以先閱讀下面的文件,會發現其實很簡單。

小程式關於圖片操作的api文件:https://developers.weixin.qq.com/miniprogram/dev/api/wx.compressImage.html

小程式關於視訊操作的api文件:https://developers.weixin.qq.com/miniprogram/dev/api/wx.saveVideoToPhotosAlbum.html

首先wxml檔案

<view class="containor">
  <view class="publish_text_area">
    <!-- 標題 -->
    <view class="text_area_title">
      <input 
        class="title_input" 
        placeholder
="請輸入標題" maxlength="25" placeholder-style="color:#b3b3b3;font-size:16px;" bindinput="handleTitleInput" value="{{title}}" >
</input> <!-- 標題字數限制 --> <view class="{{ titleCount < 25 ? 'title_input_counter' : 'title_input_error_counter'
}}"
>
{{titleCount}}/25</view> </view> <!-- 內容 --> <view class="text_area_content"> <view class="area_content"> <view class="area_content_out"> <textarea class="content-textarea" placeholder="請輸入正文內容..." maxlength="255" placeholder-style="color:#b3b3b3;font-size:12px;" style="height: 8rem" bindinput="handleContentInput" value="{{content}}" /> <!-- 字數限制 --> <view class="{{ contentCount < 255 ? 'content_textarea_counter' : 'content_textarea_error_counter'}}">{{contentCount}}/255</view> </view> </view> </view> </view> <view class="publish_imgs_area"> <!-- 圖片 --> <view class="imgs_area" wx:for="{{images}}" wx:key="*this"> <view class="iamge_item"> <image class="iamge_content" src="{{item}}" data-id="{{index}}" mode="aspectFill" bindtap="previewIamge" /> <image class="iamge_cancel" src="./images/cancel.png" mode="aspectFill" data-id="{{index}}" bindtap="deleteImage" /> </view> </view> <!-- 視訊 --> <view class="video_area" wx:if="{{video != ''}}"> <video class="video_item" src="{{video}}" controls ></video> <!-- 防止視訊元件層級太高,導致部分機型覆蓋懸浮按鈕 --> <cover-image class="video_delete" src="./images/video_del.png" mode="aspectFill" bindtap="videoDelete" /> </view> <!-- 圖片上傳圖片按鈕 --> <view class="imgs_area" bindtap="chooseImage" wx:if="{{images.length < 9 && video == ''}}"> <view class="iamge_item"> <image class="iamge_content" src="./images/upload.png" mode="aspectFill" /> </view> </view> <!-- 視訊上傳圖片按鈕 --> <view class="imgs_area" bindtap="chooseVideo" wx:if="{{video == '' && images.length == 0}}"> <view class="iamge_item"> <image class="iamge_content" src="./images/video.png" mode="aspectFill" /> </view> </view> </view> <view class="btn_all_area"> <button class="btn_area" type="primary" bindtap="submitClick" >提交</button> <button class="btn_area" type="warn" bindtap="resetClick" >重置</button> </view> </view>

接下來wxss檔案

page {
    background-color: #f1efef;
}

.containor {
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.publish_text_area {
    background-color: #ffffff;
    display: flex;
    flex-direction: column;
    justify-content: center;
    margin:20rpx 20rpx 6rpx 20rpx;
    border-radius: 15rpx;
}

.text_area_title {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin: 10rpx;
}

.text_area_content {
    
}

.title_input {
    font-size: 30rpx;
    width:590rpx;
}

.title_input_counter {
    font-size:32rpx;
    color:#b3b3b3;
    margin-top:5rpx;
}

.title_input_error_counter {
    font-size:32rpx;
    color:#ce2f2f;
    margin-top:5rpx;
}

.area_content {
    border-top: 1rpx solid #f1efef;
    margin-left: 10rpx;
    margin-right: 10rpx;
}

.area_content_out {
    /* border-top: 1px solid #f1efef; */
    margin-top: 10rpx;
}

.content-textarea {
    width: 690rpx;
    font-size: 24rpx;
}

.content_textarea_counter {
    color:#d4d0d0;
    font-size:30rpx;
    text-align:right;
}

.content_textarea_error_counter {
    color:#ce2f2f;
    font-size:30rpx;
    text-align:right;
}
/* 圖片部分 */
.publish_imgs_area{
    background-color: #ffffff;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    flex-wrap: wrap;
    border-radius: 15rpx;
    margin: 20rpx;
    padding-left: 8rpx;
    padding-top: 8rpx;
    padding-bottom: 8rpx;
    /* height: 450rpx; */
}

.iamge_item {
    width: 225rpx;
    height: 225rpx;
    padding: 4rpx;
}

.iamge_content{
    width: 223rpx;
    height: 223rpx;
    border-radius: 15rpx;
    border: 1px solid #f1efef;
}

.iamge_cancel{
    width:40rpx;
    height:40rpx;
    border-radius:50%;
    position:relative;
    top:-259rpx;
    right:-204rpx;
    z-index:800;
}

/* 視訊部分樣式 */
.video_area {
    width: 700rpx;
    position: relative;
}

.video_item {
    width: 700rpx;
}
.video_delete {
    width: 50rpx;
    height: 50rpx;
    position: absolute;
    top: 10rpx;
    right: 2rpx;    
}

.btn_all_area {
    background-color: #ffffff;
    display: flex;
    flex-direction: row;
    justify-content: center;
    margin:20rpx 20rpx 6rpx 20rpx;
    border-radius: 15rpx;
    /* position: absolute;
    bottom: 0; */
}

.btn_area {
    width: 350rpx;
}

最後是Js檔案

對於圖片的上傳,可以存在兩種情況:1、第一次就上傳了九張圖片;2、第一次不夠九張,第二次接著上傳。所有我們需要對這個條件就行判斷。

Page({
  /**
   * 頁面的初始資料
   */
  data: {
    // 標題數
    titleCount: 0,
    // 詳情數
    contentCount: 0,
    // 標題內容
    title: '',
    // 標題內容
    content: '',
    // 圖片列表
    images: [],
    // 視訊
    video : '',
  },

  // 圖片操作的具體函式
  ImageOperator() {
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: res =>  {
        // 上傳的圖片資料
        const imgList = res.tempFilePaths;
        // 原始的圖片資料
        const imageList = this.data.images;

        // 原來的圖片數量
        let imageLenght = imageList.length;
        // 當前的圖片數量
        let nowLenght = imgList.length;
        console.log(imageLenght);

        if ( imageLenght == 9 ) {
          console.log("數量已經有9張,請刪除在新增...");
        }
        if ( imageLenght < 9 ) {
          let images = [];
          // 獲取缺少的圖片張數
          let residue = 9 - imageLenght;
          // 如果缺少的張數大於當前的的張數  
          if ( residue >= nowLenght ) {
            // 直接將兩個數組合併為一個  
            images = imageList.concat(imgList);
          }else {
            // 否則擷取當前的陣列一部分  
            images = imageList.concat(imgList.slice(0, residue));
          }  
          this.setData({
            images
          })
        }
      }
    })
    
  },

  // 標題操作
  handleTitleInput(event) {
    let inputValue = event.detail.value;
    // 確保標題不存在空格  
    if(inputValue.lastIndexOf(" ") != -1){
      inputValue = inputValue.substring(0, inputValue.lastIndexOf(" "));
    }
    let titleCount = inputValue.length;
    if(titleCount <= 25){
      this.setData({
        titleCount: titleCount ,
        title: inputValue
      })
    }
  },
  // 內容操作
  handleContentInput(event) {
    let textareaValue = event.detail.value;
    let contentCount = textareaValue.length;
    if(contentCount <= 255){
      this.setData({
        contentCount: contentCount,
        content: textareaValue
      })
    }
  },
  // 圖片獲取
  chooseImage() {
    if (this.data.images.length == 0) {
      wx.showToast({
        title: '視訊和圖片只能選擇上傳一種型別!',
        icon: 'none',
        duration: 2000,
        success: res => {
          this.ImageOperator()
        }
      })
    }else {
      this.ImageOperator()
    }
    
  },
  // 刪除圖片
  deleteImage(event) {
    //獲取資料繫結的data-id的資料
    const nowIndex = event.currentTarget.dataset.id;
    let images = this.data.images;
    images.splice(nowIndex, 1);
    this.setData({
      images
    })
  },
  // 預覽圖片
  previewIamge(event) {
    const nowIndex = event.currentTarget.dataset.id;
    const images = this.data.images;
    wx.previewImage({
      current: images[nowIndex],  //當前預覽的圖片
      urls: images,  //所有要預覽的圖片
    })
  },
  // 上傳視訊
  chooseVideo() {
    // 彈層  
    wx.showToast({
      title: '視訊和圖片只能選擇上傳一種型別!',
      icon: 'none',
      duration: 2000,
      success: res => {
        wx.chooseVideo({
          sourceType: ['album', 'camera'],
          compressed: true,
          maxDuration: 10,
          camera: 'back',
          success: res => {
            console.log(res);
            const video = res.tempFilePath;
            this.setData({video})
          }
        })
      }
    })
  },
  // 刪除視訊
  videoDelete(){
    wx.showModal({
      title: '警告',
      content: '確定要刪除該視訊嗎',
      success: res => {
        if (res.confirm) {
          this.setData({
            video: ''
          })
        }
      }
    })
  },
  // 表單提交事件
  submitClick() {

  },
  // 重置表單
  resetClick() {
    wx.showModal({
      title: '警告',
      content: '重置表單將需要重新上傳資料',
      success: res => {
        if (res.confirm) {
          this.setData({
            titleCount: 0,
            contentCount: 0,
            title: '',
            content: '',
            images: [],
            video : ''
          })
        }
      }
    })
  }
})

這樣就實現了,程式碼還有很多需要優化的地方,如果需要請自行斟酌使用!