基于云存储的电子书橱-小程序云开发

云存储的小程序项目无须自行搭建服务器,可以在小程序前端直接使用云开发API下载云存储中的电子书资源到本地设备进行使用。

创建云模板项目

在任意盘符下创建一个空白文件夹cloudBooks.然后填入AppID和选择“小程序-云开发”

选择“详情”->"调试基础库" 选择人数最多的

打开miniprogram文件夹中的app.json文件,将其中的 "style": "v2"去掉,page中只保留 "pages/index/index"

打开pages文件,删除index以外的所有目录

删除images文件中的图片

components文件是用于聊天用的,可以删除 

 

 清理完多余文件之后如下图所示

迁移项目 

需要将之前做的booksDemo相关文件合并到当前新建的云项目中。

将booksDemo中的pages文件夹内的所有内容复制,粘贴过来,其中index文件全部替换。

将booksDemo中的app.json和app.wxss文件替换过来。

部署云存储

打开云开发控制台,选择“存储”面板,新建文件夹books,然后点击“上传文件”进入并将需要的电子书资源PDF格式上传到云文件存储库中。

 

云文件存储库最大允许免费存储5GB容量的文件。

 部署云数据库

 将图书数据输入到Excel表格里面,第一行为标题

将Excel表格文件另存为CSV格式

安装Notepad++文件,打开CSV文件,转换为utf8编码格式并保存

打开云开发控制台,创建一个新的数据集,如books

检查books数据集的权限,确认权限选择的是“所有用户可读,仅创建者及管理员可写”。

导入CSV文件,完成

在Excel中填写字段:title,author,price,isbn,coverurl,fileid云文件存储库中的文件ID

coverurl为图书封面地址,filedid为云存储数据库中的file ID 

将Excel表格转换为 utf8编码格式 后,在云开发控制台创建一个集合名称

上传books.csv文件

 


 首页改造

展示图书列表 

首先需要删除原来的临时数据,修改index.js文件,清空其中的data初始数据

Page({
  /*
   * 页面的初始数据
   */
  data: {
    isDownloading:false, /* 没有下载 */
    percentNum:0,
    bookList:[ ]
  },
// index.js
// 获取应用实例
wx.cloud.init() 
const db = wx.cloud.database()
const books = db.collection('books')

修改index.js文件中的onLoad函数


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

上述代码表示从云数据集books中读取图片信息

修改index.wxml页面的代码,为wx:for 循环内部的元素匹配数据集里的字段

 Cloud API isn't enabled, please call wx.cloud.init first 这个错误的意思就是云环境还没有初始化就调用其它的云api了,因此需要先初始化,也就是让我们先 wx.cloud.init() 进行初始化,最简单的办法就是直接在最前面初始化
 


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

点击跳转图书详情页

创建页面intro,用于显示图书详情

在app.json创建intro页面:

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

然后在index.wxml页面修改点击事件:

<!-- 图书单元区域设计 -->

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

然后在index.js文件中添加自定义函数showBookIntro

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

图书详情页改造 

页面设计

将index.wxml里面的蒙层代码剪切,粘贴过来使用

<!--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>

 将index.js文件中data里面的初始数据剪切,粘贴到当前intro.js文件的data中

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

同样将index.wxsss文件中关于蒙层的样式代码剪切,粘贴到当前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; /*分散布局*/
}

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

 然后在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代码:


/* 图书详细信息区域 */
.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;
}

 页面逻辑

intro.js文件,在其顶部添加代码

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

修改intro.js中的onLoad函数

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

 上面代码表示根据页面跳转过来时所携带的图书ID查找云数据集books中该图书相关信息。

阅读图书功能

修改intro.js代码,将原先在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)
    }
  },

})

此时点击按钮会检测当前这本书是否已经下载过了,如果已经下载过了,则直接打开阅读;如果没有下载过,则显示下载进度条蒙层进行下载

所选择的电子书已经从云存储空间中下载到本地。用户要注意小程序只允许下载,保存10MB以内大小的文件,必要时可以在微信web开发者工具中清除文件缓存

完整代码: 

应用文件代码

app.json文件

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

首页代码显示 

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})
      }
    })
  },
})

 图书详情页代码展示

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)
    }
  },

})

猜你喜欢

转载自blog.csdn.net/m0_46965984/article/details/124286587