Quick Start for WeChat Mini Program Cloud Development (3/4)

foreword

In the sharing of "WeChat Mini Program Cloud Development Quick Start (2/4)" , we have already done all the query and pagination of the list. It can be said that it is very easy to use for the memo. At this moment, the code boy is in my mind I have already begun to fantasize that I have reached the pinnacle of life.

Next, let’s analyze the specific steps of the requirements:
image replacement requirements

  1. Select Image
  2. upload image
  3. upload again
  4. Select Image
  5. delete picture

Here you need to manage the data of the picture, and also need to upload it to the cloud storage.

local image manipulation

Layout start

It’s been a long time since I wrote a layout style, isn’t it a bit rusty? I feel like reviewing, reviewing the past and learning the new. When we want to debug the style of a page, we first need to lock the current compilation mode:

156fd202308070946341519.png

First, put a photo icon in the image component area of ​​the head, and when the user clicks on the icon, we will select the image.

 <!-- 头部 -->
  <view class="head-bg">
  <!-- 省略无关布局 -->
    <image class="img-add" src="../../images/img_add.png"></image>
  </view>

Then configure it with a style and place the position roughly on the teacup, using position positioning.

.img-add{
  width: 50rpx;
  height: 50rpx;
  position: absolute;
  right: 65rpx;
  top: 450rpx;
}

final effect

37a1520230807094652650.png

Then bind a click event through bindtap to select the picture.

<image bindtap="chooseImg" class="img-add" src="../../images/img_add.png" />

Select Image

In this chooseImg method, you can choose an image from the local album or take a photo with the camera through wx.chooseImage().

wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], 
      sourceType: ['album', 'camera'],
      success (res) {
        // 由于是数组然后只取一张图片,所以默认取下标为0的图片
        console.log(res.tempFilePaths[0])
      }
    })

chooseImage parameter explanation:

  • count: the number of photos that can be selected, the default is 9
  • sourceType: Select the source of the picture, which can be supported by both mobile phones and cameras by default.
  • sizeType: The size of the selected image, the default is that both the original image and the compressed image are supported.
  • success(res)

replace picture

After the selection is completed, the next step is to display the picture. First, define a variable in data to store the selected picture path.

data: {
    topImgUrl:''
  }

Then store the obtained value in this variable

chooseImg(){
    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        that.data.topImgUrl = res.tempFilePaths[0]
      }
    })
  }

Previously the background image was set by using the background-image property in css.

.head-bg {
  width: 750rpx;
  height: 540rpx;
  background-image: url('https://6465-demo-3gf9i3wu06a03ab1-1306451997.tcb.qcloud.la/head_bg.png');
  background-size: 100% 100%;
}

Applets cannot pass parameters to css but only in wxml, so we need to write them as inline styles.

 <!-- 头部 -->
  <view class="head-bg" style="background-image: url('https://6465-demo-3gf9i3wu06a03ab1-1306451997.tcb.qcloud.la/head_bg.png');" >
   <!-- 省略无关布局 -->
  </view>

Then replace topImgUrl with the image path

<!-- 头部 -->
   <view class="head-bg" style="background-image: url('{
   
   {topImgUrl}}');" >
    <!-- 省略无关布局 -->
  </view>

Then run it to see the effect:

d17a6202308070947325662.png

At this time, we will find that the user does not have a picture at the beginning, so we need to set a default value for topImgUrl.

 data: {
    topImgUrl:'https://6465-demo-3gf9i3wu06a03ab1-1306451997.tcb.qcloud.la/head_bg.png'
  }

012d4202308070947444288.png

Then we choose a photo to try to see the effect, we will find that there is still no effect, because local images are not supported. Then at this time we need to upload to cloud storage.

Image upload cloud storage

Cloud file storage, built-in CDN acceleration, supports direct upload/download on the front end, and can be visually managed on the cloud development console.

Cloud Storage Visualization

This default image is actually the one we manually uploaded to the cloud storage before. Open the cloud development control panel and select "Storage" to see the previously uploaded background image and bubble image.

a02dc20230807094755314.png

In addition to directly managing files, it also supports setting permissions like a cloud database.

cab1a202308070948051024.png

And it also supports cache configuration and supports multiple configuration strategies.

5511c202308070948144488.png

upload to cloud storage

Not much to say, next, upload the selected pictures to the cloud storage through the applet. Here, use wx.cloud.uploadFile to upload the local resources to the cloud storage space.

wx.cloud.uploadFile({
  cloudPath: 'example.png',
  filePath: '', // 文件路径
}).then(res => {
  // get resource ID
  console.log(res.fileID)
})

uploadFile parameter explanation:

  • cloudPath: path name
  • filePath: file path
  • return value res

By uploading the code combined with the selected image code just now

chooseImg: function () {
    const that = this
    wx.chooseImage({
      count: 1, // 只选择一张图片
      sizeType: ['compressed'], // 使用压缩图
      sourceType: ['album', 'camera'], // 支持照相,相册
      success: function (res) {
        const filePath = res.tempFilePaths[0] //上传第一张图片
        // 生成规则:文件夹路径 + 时间戳 + 随机数 + 文件后缀
        const cloudPath = `top-img/${Date.now()}-${Math.floor(Math.random(0, 1) * 100000)}` + filePath.match(/.[^.]+?$/)[0]
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            console.log('上传成功后获得的res:', res)
            that.setData({
              topImgUrl:res.fileID
            })
          },
          fail:err=>{
            console.log(err)
          }
        })
      }
    })
  }

Upload successfully res

2ba1b202308070948332344.png

Storage management, a folder is automatically generated and the pictures are uploaded here

21fbb202308070948422641.png

delete online files

Of course, if you upload it, you must delete it, because there will always be pictures you don’t like that need to be deleted. Requires wx.cloud.deleteFile to delete files from cloud storage.

wx.cloud.deleteFile({
  fileList: ['cloud://demo-3gf9i3wu06a03ab1.6465-demo-3gf9i3wu06a03ab1-1306451997/top-img/1627462991919-39954.png']
}).then(res => {
  console.log(res.fileList)
})

deleteFile parameter explanation:

  • fileList: file ID array
  • return value res

Next, I will use the file ID just now to see the returned result

097d2202308070948599312.png

get online link

When the FileID is obtained, it still cannot be displayed. At this time, it is necessary to obtain the image path through the FileID, and use wx.cloud.getTempFileURL to exchange the cloud file ID for a real link.

wx.cloud.getTempFileURL({
  fileList: ['cloud://xxx', 'cloud://yyy'],
  success: res => {
    // get temp file URL
    console.log(res.fileList)
  },
  fail: err => {
    // handle error
  }
})

getTempFileURL parameter explanation:

  • fileList: file ID array
  • return value res

Next, I will use the file ID just now to see the returned result

a04fd202308070949139927.png

Next we need to marry the path, the final code

chooseImg: function () {
    const that = this
    // 1. 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const filePath = res.tempFilePaths[0] //上传第一张图片
        const cloudPath = `top-img/${Date.now()}-${Math.floor(Math.random(0, 1) * 100000)}` + filePath.match(/.[^.]+?$/)[0]
        console.log(cloudPath)
        // 2. 上传图片
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            // 3. 获取链接
            wx.cloud.getTempFileURL({
              fileList: [res.fileID],
              success: res => {
                that.setData({
                  topImgUrl: res.fileList[0].tempFileURL
                })
              }
            })
          }
        })
      }
    })
  }

Finally uploaded to the picture after several twists and turns and displayed it

afda7202308070949285143.png

I believe that when you see this, you will definitely complain about why it is so troublesome? Can it be simpler?
Of course, we can omit one step, which is to get the link, because the src attribute of the image component supports the file ID, so you need to get the link.

In addition, you can see that if it is a custom header picture bubble, there is no meaning of existence, because it will block the content of the picture itself, so we will make an adjustment, if there is a custom picture, a picture will be displayed, if not Just follow the original design.

  1. Modify the layout and abstract the style
/* 头部大小 */
.head {
  width: 750rpx;
  height: 540rpx;
}
/* 头部背景 */
.head-bg {
  background-image: url('https://6465-demo-3gf9i3wu06a03ab1-1306451997.tcb.qcloud.la/head_bg.png');
  background-size: 100% 100%;
}

  1. The specific layout structure changes, and the display and hiding are controlled by the parameter topImgUrl
<!-- 头部 -->
  <image wx:if="{
   
   {fileID}}" src="{
   
   {fileID}}" class="head"></image>
  <view wx:if="{
   
   {! fileID}}" class="head head-bg" >
    <view bindtap="randomMsg" class="head-bubble">
      <!-- 头像 -->
      <view class="user-avatar">
        <open-data type="userAvatarUrl"></open-data>
      </view>
      <!-- 问候语 -->
      <text>,{
   
   {message}}</text>
    </view>
    <image bindtap="chooseImg" class="img-add" src="../../images/img_add.png" />
  </view>

  1. Upload image complete code
chooseImg: function () {
    const that = this
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const filePath = res.tempFilePaths[0] //上传第一张图片
        const cloudPath = `top-img/${Date.now()}-${Math.floor(Math.random(0, 1) * 100000)}` + filePath.match(/.[^.]+?$/)[0]
        // 上传图片
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
          // 设置文件ID
            that.setData({
              fileID: res.fileID
            })
          }
        })
      }
    })
  },

Although the effect has been achieved, there is still a problem that the default picture will still be displayed next time when you come in, and the data will not be saved, so at this time we need to use the database operations we have learned. How to manage the background data in the cloud database?

Background image management

Don't underestimate this function. Although we have implemented the business of the small program before this function, there are still some things that need to be considered comprehensively in data logic processing.

According to the usual practice, first analyze the specific implementation ideas:

  1. Create a new background collection to store background information
  2. A record needs to be added when saving the background
  3. When replacing the background, you need to delete and add
  4. When deleting the background, you need to delete the picture at the same time
  5. The user enters the query background data display

The above used are only the content learned in the previous shared content. This time, using the same knowledge to realize different businesses is equivalent to a process of consolidating and reviewing your previous knowledge and strengthening your understanding of these knowledge points. impression.

Create a new data set

Used to store background image information

87ed3202308070949526156.png

Create a new one called background to store and manage background data, and then let's look at the permissions:

e87fa202308070950009981.png

Because in actual business requirements, this background can only be seen by the current user, so the default permissions are suitable for our current business and do not need to be adjusted.

Define the operation interface

061b2202308070950117624.png

The applet needs to operate the background database, so we create a background.js in the api folder to write related database operation methods.

// 获取背景
function getBackground() {
}

// 添加背景
function addBackground(data)
}

// 删除背景
function delBackground(id) {
}

// 导出声明
export {
  getBackground,
  addBackground,
  delBackground
}

According to actual needs, the decibel definition is used to obtain the background, add the background, delete the background, and then make an export statement at the end in order to allow other js to be imported and used.

save upload background

First implement the method of adding data

// 添加背景
function addBackground(data) {
  // 1. 获取数据库引用
  const db = wx.cloud.database()
  // 2. 找到集合获取数据
  const background = db.collection('background')
  // 3. 添加创建时间
  data.createTime = db.serverDate()
  // 4. 集合添加数据
  return background.add({data})
}

Here I have made a small meal for everyone, using serverDate to get the server time, which can be used for query conditions, updating field values ​​or field values ​​when adding records.

serverDate parameter description:

  • offset: in millimeters, you can set the time offset

Then go to the list page to use it, first introduce the file method:
add to the head of list.js

import {
  addBackground
} from '../../api/background.js'

After selecting the image and uploading it, use the add method:

chooseImg: function () {
    const that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const filePath = res.tempFilePaths[0] //上传第一张图片
        const cloudPath = `top-img/${Date.now()}-${Math.floor(Math.random(0, 1) * 100000)}` + filePath.match(/.[^.]+?$/)[0]
        console.log(cloudPath)
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            let data = {
              fileID: res.fileID
            }
            that.setData(data)
            addBackground(data)
          }
        })
      }
    })
  },

After the add operation, the data is added to the database:

9b867202308070950464930.png

We can edit the createTime field:

6f6a2202308070950559891.png

ba4c6202308070951012698.png

You can see that this is a time type field parameter.
After the addition is complete, there are two more things to do:

  1. Check background information when entering
  2. When replacing the background, delete it first and then add it

Query background information

First implement the query data method:

// 获取背景
function getBackground() {
  // 1. 获取数据库引用
  const db = wx.cloud.database()
  // 2. 找到集合获取数据
  const background = db.collection('background')
  // 3. 查询集合数据
  return background.get()
}

Introduce the query method in list.js:

import {
  addBackground,
  getBackground
} from '../../api/background.js'在 onLoad 进行查询调用:

Make a query call in onLoad:

/**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取背景图
    this.getBackground()
    // 获取问候语
    this.randomMsg()
  },
  // 获取背景图
  getBackground(){
    getBackground().then(res => {
      // 判断是否有数据
      if (res.data.length) {
        this.setData({
          fileID:res.data[0].fileID // 获取第一条数据
        })
      }
    })
  }

When the user enters the list page, the uploaded background will be displayed.

Replace background information

Here it is necessary to delete first and then add, of course, it can also be implemented in a modified way. It should be noted here that no matter what method is used, the previous background files need to be deleted, and useless pictures need to be cleaned up in time, otherwise server resources will be occupied in vain, and storage resources will need to be charged. Although storage costs are not expensive, it is necessary to maintain a good saving habit.

First implement the delete method:

// 删除背景数据同时删除背景图片
function delBackground(id,fileID) {
  // 1. 获取数据库引用
  const db = wx.cloud.database()
  // 2. 获取集合对象
  const background = db.collection('background')
  // 3. 删除背景图片
  wx.cloud.deleteFile({
    fileList: [fileID]
  })
  // 4. 删除当条背景数据
  return background.doc(id).remove()
}

Introduce the delete method in lis.js:

import {
  addBackground,
  getBackground,
  delBackground
} from '../../api/background.js'

Here, because the deletion requires an id, the id needs to be saved when obtaining the background

getBackground(){
    getBackground().then(res => {
      if (res.data.length) {
        const background = res.data[0]
        this.data.background = background
        this.setData({
          fileID:background.fileID
        })
      }
    })
  }

Then judge whether there is an id in the logic of selecting the picture, and if so, prove that the picture has been uploaded before and delete it

chooseImg: function () {
    const that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const filePath = res.tempFilePaths[0] //上传第一张图片
        const cloudPath = `top-img/${Date.now()}-${Math.floor(Math.random(0, 1) * 100000)}` + filePath.match(/.[^.]+?$/)[0]
        console.log(cloudPath)
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            let data = {
              fileID: res.fileID
            }
            that.setData(data)
            addBackground(data)
            // 判断是否之前上传过图片
            if(that.data.background){
              let id = that.data.background._id
              let fileID = that.data.background.fileID
              delBackground(id,fileID)
            }
          }
        })
      }
    })
  }

After writing the JS logic processing code, I accidentally found that the ICON for taking pictures was missing after uploading the picture. Later, I checked the layout code and found that the ICON for taking pictures was in the layout of the unuploaded picture state, so it was not hidden. We need to move the layout remove.

<!-- 头部 -->
  <image wx:if="{
   
   {fileID}}" src="{
   
   {fileID}}" class="head"></image>
  <view wx:if="{
   
   {!fileID}}" class="head head-bg" >
    <view bindtap="randomMsg" class="head-bubble">
      <!-- 头像 -->
      <view class="user-avatar">
        <open-data type="userAvatarUrl"></open-data>
      </view>
      <!-- 问候语 -->
      <text>,{
   
   {message}}</text>
    </view>
    <!-- 原来的位置 -->
    <!-- <image bindtap="chooseImg" class="img-add" src="../../images/img_add.png" /> -->
  </view>
  <image bindtap="chooseImg" class="img-add" src="../../images/img_add.png" />

You're done! Ma Zai was secretly happy, so he secretly put on a photo of him and Ma Niu. Mazai thought about it before and after, "This function is still very necessary!".

ccbb8202308070951405717.png

Summarize

  1. Learned the picture operation of the applet: wx.chooseImage(), choose the picture
  2. Small program picture cloud storage management:
    1. wx.cloud.uploadFile: upload file
    2. wx.cloud.deleteFile : delete a file
    3. wx.cloud.getTempFileURL: get online link
  3. The previously learned database: adding, querying, and deleting operations are combined to achieve a requirement

Guess you like

Origin blog.csdn.net/weixin_64051447/article/details/132295558