1. 程式人生 > >黃秀傑--小程式實現選擇圖片九宮格帶預覽

黃秀傑--小程式實現選擇圖片九宮格帶預覽

效果圖

資料:

依賴介面wx.upload、chooseImage與preview 資料請求通過LeanCloud完成

圖片選擇:

前端處理:

1.儲存images陣列為已選擇圖片 2.選擇了更多圖片後concat陣列 3.預覽圖集 4.leancloud上傳多圖,目測順序一致

js程式碼

const AV = require('../../../utils/av-weapp.js')
var that;
Page({
    data: {
        images: [],
        uploadedImages: [],
        imageWidth: getApp().screenWidth / 4
- 10 }, onLoad: function (options) { that = this; var objectId = options.objectId; console.log(objectId); }, chooseImage: function () { // 選擇圖片 wx.chooseImage({ sizeType: ['compressed'], sourceType: ['album', 'camera'], // 可以指定來源是相簿還是相機,預設二者都有
success: function (res) { // 返回選定照片的本地檔案路徑列表,tempFilePath可以作為img標籤的src屬性顯示圖片 var tempFilePaths = res.tempFilePaths; console.log(tempFilePaths); that.setData({ images: that.data.images.concat(tempFilePaths) }); } }) }, previewImage: function
()
{ // 預覽圖集 wx.previewImage({ urls: that.data.images }); }, submit: function () { // 提交圖片,事先遍歷圖集陣列 that.data.images.forEach(function (tempFilePath) { new AV.File('file-name', { blob: { uri: tempFilePath, }, }).save().then( // file => console.log(file.url()) function(file) { // 先讀取 var uploadedImages = that.data.uploadedImages; uploadedImages.push(file.url()); // 再寫入 that.setData({ uploadedImages: uploadedImages }); console.log(uploadedImages); } ).catch(console.error); }); wx.showToast({ title: '評價成功', success: function () { wx.navigateBack(); } }); }, delete: function (e) { var index = e.currentTarget.dataset.index; var images = that.data.images; images.splice(index, 1); that.setData({ images: images }); } })

wxml程式碼

<viewclass="gallery"><viewclass="item"wx:for="{{images}}"wx:key=""><imagestyle="width: {{imageWidth}}px; height: {{imageWidth}}px"src=" {{item}}"bindtap="previewImage"mode="aspectFill" /><!-- 刪除按鈕 --><viewclass="delete"bindtap="delete"data-index="{{index}}"><imagestyle="left: {{imageWidth / 2 - 10}}px;"src="/images/icon_delete.png" /></view></view><viewclass="item"><imagestyle="width: {{imageWidth}}px; height: {{imageWidth}}px"src="/images/icon_add.png"class="button-upload"bindtap="chooseImage" /></view></view><buttontype="primary"bindtap="submit">提交</button>

wxss程式碼

/*畫廊*/
.gallery {
    /*margin-bottom: 100rpx;*/
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
}

/*每張圖片所佔容器*/
.item {
    position: relative;
    margin: 5px;
}

/*刪除按鈕*/
.delete {
    position: absolute;
    height: 20px;
    bottom: 0;
    width: 100%;
    background: #ccc;
    opacity: .8;
}

.delete image {
    position: absolute;
    width: 20px;
    height: 20px;
}