Electronic bookcase based on cloud storage - applet cloud development

The small program project of cloud storage does not need to build a server by itself , and can directly use the cloud development API on the front end of the small program to download the e-book resources in the cloud storage to the local device for use.

Create a cloud template project

Create a blank folder cloudBooks under any drive letter. Then fill in the AppID and select "Mini Program - Cloud Development"

Select "Details" -> "Debug Basic Library" to select the one with the largest number of people

Open the app.json file in the miniprogram folder, remove "style": "v2", and only keep "pages/index/index" in the page

Open the pages file and delete all directories except index

Delete images from the images file

The components file is used for chatting and can be deleted 

 

 After cleaning up the redundant files, as shown in the figure below

migration project 

It is necessary to merge the previously made booksDemo related files into the current new cloud project.

Copy and paste all the content in the pages folder in booksDemo, and replace all the index files.

Replace the app.json and app.wxss files in booksDemo.

Deploy cloud storage

Open the cloud development console, select the "Storage" panel, create a new folder books, and then click "Upload Files" to enter and upload the required e-book resources to the cloud file repository in PDF format.

 

 

The cloud file storage library allows free storage of files with a maximum capacity of 5GB.

 Deploy cloud database

 Enter the book data into the Excel table, the first line is the title

Save Excel spreadsheet file as CSV format

Install the Notepad++ file, open the CSV file, convert it to utf8 encoding format and save it

Open the cloud development console and create a new dataset, such as books

Check the permissions of the books dataset, and confirm that the permission is set to "Readable by all users, writable only by creators and administrators".

Import the CSV file, done

Fill fields in Excel: title, author, price, isbn, coverurl, fileid File ID from cloud file repository

coverurl is the book cover address, filedid is the file ID in the cloud storage database 

After converting the Excel table to utf8 encoding format  , create a collection name in the cloud development console :

Upload books.csv file

 

 


 Home Makeover

show book list 

First, you need to delete the original temporary data, modify the index.js file, and clear the initial data in it

Page({
  /*
   * 页面的初始数据
   */
  data: {
    isDownloading:false, /* 没有下载 */
    percentNum:0,
    bookList:[ ]
  },

 

// index.js
// 获取应用实例
wx.cloud.init() 
const db = wx.cloud.database()
const books = db.collection('books')

Modify the onLoad function in the index.js file


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    books.get({
      success:res => {
        this.setData({bookList:res.data})
      }

The above code means to read the image information from the cloud dataset books

Modify the code of the index.wxml page to match the fields in the data set for the elements inside the wx:for loop

 Cloud API isn't enabled, please call wx.cloud.init first This error means that the cloud environment has not been initialized before calling other cloud APIs, so it needs to be initialized first, that is, let us first wx.cloud.init() To initialize, the easiest way is to initialize directly at the front
 


wx.cloud.init() 
const db = wx.cloud.database()
const books = db.collection('books')

Click to jump to the book details page

Create a page intro for displaying book details

Create an intro page in app.json:

{
  "pages": [
    "pages/index/index",
    "pages/intro/intro"
  ],
  "window": {
    "navigationBarBackgroundColor": "#663366",
    "navigationBarTitleText": "我的书架"
  },
  "sitemapLocation": "sitemap.json"
}

Then modify the click event on the index.wxml page:

<!-- Book unit area design -->

  <view class="box" wx:for="{ {bookList}}" wx:key="book{ {index}}" data-id='{ {item._id}}' bindtap="showBookIntro">

Then add a custom function showBookIntro in the index.js file

// 显示图书详情
  showBookIntro:function(e){
    //获取图书ID编号
    let id = e.currentTarget.database.id
    wx.navigateTo({
      url:'../intro/intro?id='+id,
    })
  },

Book details page renovation 

page design

Cut and paste the mask code in index.wxml to use

<!--index.wxml-->
<!-- 下载时的蒙层 -->
<view class="loading-container" wx:if="{
   
   {isDownloading}}">
<text>下载中,请稍后</text>
<progress percent="{
   
   {percentNum}}" stroke-width="6" activeColor="#663366" backgroundColor="#ffffff" show-info active active-mode="forwards"></progress>
</view>

 Cut the initial data in the data in the index.js file and paste it into the data in the current intro.js file

data: {
    isDownloading:false, /* 没有下载 */
    percentNum:0
  },

Also cut and paste the mask style code in the index.wxsss file into the current intro.wxss file

/* pages/intro/intro.wxss */
/* 下载时蒙层容器 */
.loading-container{
  height: 100vh;
  background-color: silver;
  display: flex;   /* flex模型布局 */
  flex-direction: column; /*水平排列*/
  align-items: center;  
  justify-content: space-around; /*分散布局*/
}

/* 进度条 */
progress{
  width: 80%;
}

 Then add the book details of the current page to intro.wxml :

<!--pages/intro/intro.wxml-->
<!-- 图书详情 -->
<view class="intro-container" wx:else>
<!-- t图书封面图片 -->
<image src="{
   
   {book.coverurl}}" mode="widthFix"></image>
<!-- 图书信息介绍 -->
<view class="intro-box">
<text>书名:{
   
   {book.title}}</text>
<text>作者:{
   
   {book.author}}</text>
<text>价格:{
   
   {book.price}}</text>
<text>ISBN:{
   
   {book.isbn}}</text>
</view>
<!-- “开始阅读”按钮 -->
<button type="warn" bindtap="readBook">开始阅读</button>
</view>

intro.wxss code:


/* 图书详细信息区域 */
.intro-container{
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-evenly;
}

/* 图书封面图片 */
.intro-container image{
  width: 400rpx;
  margin: 20rpx;
}

/* 图书信息区域 */
.intro-box{
  display: flex;
  flex-direction: column;
}
/* 图书文字信息区域 */
.intro-box text{
  margin: 20rpx;
}

 page logic

intro.js file, add code at the top of it :

// pages/intro/intro.js
const db = wx.cloud.database()
const books = db.collection('books')

Modify the onLoad function in intro.js :

 /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    books.doc(options.id).get({
      success:res=>{
        this.setData({book:res.data})
      }
    })

 The above code means to find the relevant information of the book in the cloud dataset books according to the book ID carried when the page is redirected.

reading book function

Modify the intro.js code, cut and paste several functions in index.js.

// pages/intro/intro.js
const db = wx.cloud.database()
const books = db.collection('books')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isDownloading:false, /* 没有下载 */
    percentNum:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    books.doc(options.id).get({
      success:res=>{
        this.setData({book:res.data})
      }
    })
  },

  /* 封装showModal方法 */
  showTips:function(content){
    wx.showModal({
      title:'提醒',
      content:content,
      showCancel:false
    })
  },

  // 显示图书详情
  showBookIntro:function(e){
    //获取图书ID编号
    let id = e.currentTarget.database.id
    wx.navigateTo({
      url:'../intro/intro?id='+id,
    })
  },
  /* 打开图书 */
  openBook:function(path){
    wx.openDocument({
      filePath: path,
      success:function(res){
        console.log('打开图书成功')
      },
      fail:function(error){
        console.log(error);
      }
    })
  },
  /* 保存图书 */
  saveBook:function(id,path){
    var that = this
    wx.saveFile({
      tempFilePath: path,
      success:function(res){
        //将文件地址保存到本地缓冲中,下次直接打开
        let newPath = res.savedFilePath
        wx.setStorageSync(id, newPath)
        //打开图书
        that.openBook(newPath)
      },
      fail:function(error){
        console.log(error)
        that.showTips('文件保存失败!')
      }
    })
  },
/* 阅读图书 */
  readBook:function(e){
    var that = this
    //获取当前点击图书的ID
    let id = this.data.book._id
    
    //查看本地缓存
    let path = wx.getStorageSync(id)
    //未曾下载过
    if(path=='')
    {
      //切换到下载时的蒙层
      that.setData({
        isDownloading:true
      })

      // 获取当前点击的图书的URL地址
      let fileid = this.data.book.fileid

      //先下载图书
      const downloadTask = wx.cloud.downloadFile({
       fileID:fileid,
        success:res =>{
          
          //下载成功
          if(res.statusCode == 200){
            //获取地址
            path = res.tempFilePath
            //保存并打开图书
            that.saveBook(id,path)
          }
          //连上了服务器,下载失败
          else{
            that.showTips('暂时无法下载!')
          }
        },

        //请求失败
        fail:err=>{
          that.showTips('无法连接到服务器!')
        },
        complete:res =>{
          // 关闭下载时的蒙层
          this.setData({
            isDownloading:false
          })
        }
      })
      //监听当前文件的下载速度
      downloadTask.onProgressUpdate(function(res){
        let progress = res.progress;
        that.setData({
          percentNum:progress
        })
      })
    }

    //之前下载过的,直接打开
    else{
      //打开图书
      that.openBook(path)
    }
  },

})

At this time, click the button to check whether the current book has been downloaded. If it has been downloaded, it will be opened and read directly; if it has not been downloaded, the download progress bar will be displayed for downloading.

The selected e-book has been downloaded from the cloud storage space to the local. Users should note that the applet is only allowed to download and save files with a size of less than 10MB. If necessary, the file cache can be cleared in the WeChat web developer tool

Full code: 

app file code

app.json file

{
  "pages": [
    "pages/index/index",
    "pages/intro/intro"
  ],
  "window": {
    "navigationBarBackgroundColor": "#663366",
    "navigationBarTitleText": "我的书架"
  }
}

Home code display 

index.wxml



<!-- stroke-width表示进度条宽度 show-info表示进度条数-->

<!-- 图书展示容器 -->
<view class="book-container">
<!-- 图书单元区域设计 -->
  <view class="box" wx:for="{
   
   {bookList}}" wx:key="book{
   
   {index}}" data-id='{
   
   {item._id}}' bindtap="showBookIntro">
   <!-- 图书封面 -->
    <image src="{
   
   {item.coverurl}}"></image>
    <text>{
   
   {item.title}}</text>
  </view>
</view>

index.wxss 

/**index.wxss**/
/* 图书展示容器 */
.book-container{
  display: flex;
  flex-direction: row;  /*水平排列*/
  flex-wrap: wrap;      /*允许换行*/
}

/* 图书单元区域样式 */
.box{
  width:50%;
  height: 400rpx;
  display: flex;
  flex-direction: column; /*垂直排列*/
  align-items: center;   /*水平方向居中*/
  justify-content: space-around;/*分散布局*/
}
/* 图书封面图片样式 */
image{
  width: 200rpx;
  height: 300rpx;
}
/* 图书标题文本样式 */
text{
  text-align: center;
}

index.js

// index.js
// 获取应用实例
wx.cloud.init()
const db = wx.cloud.database()
const books = db.collection('books')
Page({
  /*
   * 页面的初始数据
   */
  data: {
    bookList:[ ]
  },
  // 显示图书详情
  showBookIntro:function(e){
    //获取图书ID编号
    let id = e.currentTarget.database.id
    wx.navigateTo({
      url:'../intro/intro?id='+id,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    books.get({
      success:res => {
        //console.log(res.data)
        this.setData({bookList:res.data})
      }
    })
  },
})

 Book details page code display

intro.wxml

<!--pages/intro/intro.wxml-->
<!-- 下载时的蒙层 -->
<view class="loading-container" wx:if="{
   
   {isDownloadind}}">
<text>下载中,请稍候</text>
<progress percent="{
   
   {percentNum}}" stroke-width="6" activeColor="#663366" backgroundColor="#FFFFFE" show-info active active-mode="forwards"></progress>
</view>

<!-- 图书详情 -->
<view class="intro-container" wx:else>
<!-- t图书封面图片 -->
<image src="{
   
   {book.coverurl}}" mode="widthFix"></image>
<!-- 图书信息介绍 -->
<view class="intro-box">
<text>书名:{
   
   {book.title}}</text>
<text>作者:{
   
   {book.author}}</text>
<text>价格:{
   
   {book.price}}</text>
<text>ISBN:{
   
   {book.isbn}}</text>
</view>
<!-- “开始阅读”按钮 -->
<button type="warn" bindtap="readBook">开始阅读</button>
</view>

intro.wxss 

/* pages/intro/intro.wxss */
/* 下载时蒙层容器 */
.loading-container{
  height: 100vh;
  background-color: silver;
  display: flex;   /* flex模型布局 */
  flex-direction: column; /*水平排列*/
  align-items: center;  
  justify-content: space-around; /*分散布局*/
}
/* 图书详细信息区域 */
.intro-container{
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-evenly;
}

/* 图书封面图片 */
.intro-container image{
  width: 400rpx;
  margin: 20rpx;
}

/* 图书信息区域 */
.intro-box{
  display: flex;
  flex-direction: column;
}
/* 图书文字信息区域 */
.intro-box text{
  margin: 20rpx;
}

/* 进度条 */
progress{
  width: 80%;
}

intro.js 

// pages/intro/intro.js
const db = wx.cloud.database()
const books = db.collection('books')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isDownloading:false, /* 没有下载 */
    percentNum:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取当前图书信息
    books.doc(options.id).get({
      success:res=>{
        this.setData({book:res.data})
      }
    })
  },

  /* 封装showModal方法 */
  showTips:function(content){
    wx.showModal({
      title:'提醒',
      content:content,
      showCancel:false
    })
  },

  // 显示图书详情
  showBookIntro:function(e){
    //获取图书ID编号
    let id = e.currentTarget.database.id
    wx.navigateTo({
      url:'../intro/intro?id='+id,
    })
  },
  /* 打开图书 */
  openBook:function(path){
    wx.openDocument({
      filePath: path,
      success:function(res){
        console.log('打开图书成功')
      },
      fail:function(error){
        console.log(error);
      }
    })
  },
  /* 保存图书 */
  saveBook:function(id,path){
    var that = this
    wx.saveFile({
      tempFilePath: path,
      success:function(res){
        //将文件地址保存到本地缓冲中,下次直接打开
        let newPath = res.savedFilePath
        wx.setStorageSync(id, newPath)
        //打开图书
        that.openBook(newPath)
      },
      fail:function(error){
        console.log(error)
        that.showTips('文件保存失败!')
      }
    })
  },
/* 阅读图书 */
  readBook:function(e){
    var that = this
    //获取当前点击图书的ID
    let id = this.data.book._id
    
    //查看本地缓存
    let path = wx.getStorageSync(id)
    //未曾下载过
    if(path=='')
    {
      //切换到下载时的蒙层
      that.setData({
        isDownloading:true
      })
      //先下载图书
      const downloadTask = wx.cloud.downloadFile({
       fileID:fileid,
        success:res =>{
          // 关闭下载时的蒙层
          this.setData({
            isDownloading:false
          })
          //下载成功
          if(res.statusCode == 200){
            //获取地址
            path = res.tempFilePath
            //保存并打开图书
            that.saveBook(id,path)
          }
          //连上了服务器,下载失败
          else{
            that.showTips('暂时无法下载!')
          }
        },

        //请求失败
        fail:err=>{
           // 关闭下载时的蒙层
           this.setData({
            isDownloading:false
          })
          that.showTips('无法连接到服务器!')
        },
      })
      //监听当前文件的下载速度
      downloadTask.onProgressUpdate(function(res){
        let progress = res.progress;
        that.setData({
          percentNum:progress
        })
      })
    }

    //之前下载过的,直接打开
    else{
      //打开图书
      that.openBook(path)
    }
  },

})

 

Guess you like

Origin blog.csdn.net/m0_46965984/article/details/124286587