小程序中搜索文件,閱覽pdf,分享文件鏈接,評論表情符號

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/hotqin888/article/details/84111389

 小程序主要是作爲客戶端展示數據,我們在工程上的應用比如:現場設代,檢索圖紙,查閱規範,查閱監理紀要等。

然後像百度網盤那樣,發送文件鏈接給好友或羣,別人可以通過鏈接直接打開。效果如下:

文章列表

文章正文

檢索規範

分享文件鏈接

好友收到鏈接

發佈文章和圖片

評論和點贊

// detail js
//引入本地json數據,這裏引入的就是第一步定義的json數據
const app = getApp()
var util = require('../../utils/util.js');
let wxparse = require("../../wxParse/wxParse.js");
Page({
  data: {
    dkheight: 300,
    dkcontent: "",
    leassonTilte: '',
    time: '',
    id: '',
    liked: true,
    inputVal: '',
    hidden: true,
    //畫布
    canvasHidden: true, //設置畫板的顯示與隱藏,畫板不隱藏會影響頁面正常顯示
    shareImgPath: '', //用於儲存canvas生成的圖片

    page: 2,
    page_size: 10,
    isShowLoadmore: false,
    isShowNoDatasTips: false,
    endloading: false,
    focus: false,

    open: true,

    shop: [],
    shop_item: {},
    shop_num: {},
    //  發表評論
    releaseFocus: true,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  /**
   * 生命週期函數--監聽頁面加載
   */
  onLoad: function(options) {
    console.log(options)
    this.setData({
      Id: options.id,
      Title: options.title,
      actIndex: options.actIndex
    })
    if (options.actindex=='standard'){
      this.setData({
        Title: options.numtitle,
      })
    }
    // 獲得高度
    let winPage = this;
    wx.getSystemInfo({
      success: function(res) {
        let winHeight = res.windowHeight;
        // console.log(winHeight);
        winPage.setData({
          dkheight: winHeight - winHeight * 0.05 - 80
        })
      }
    });
    var that = this;
    //獲取用戶設備信息,屏幕寬度
    wx.getSystemInfo({
      success: res => {
        that.setData({
          screenWidth: res.screenWidth
        })
        // console.log(that.data.screenWidth)
      }
    })
    // 登錄
    // wx.login({
    //   success: res => {
    //     // 發送 res.code 到後臺換取 openId, sessionKey, unionId
    //     if (res.code) {
    //       var getData = wx.request({
    //         url: 'https://。。。/v1/wx/getwxarticle/' + options.id,
    //         header: {
    //           "Content-Type": "application/x-www-form-urlencoded"
    //         },
    //         data: {
    //           code: res.code,
    //           app_version: 1.1, //閱覽版用的
    //         },
    //         // header: {
    //         //   'content-type': 'application/json' // 默認值
    //         // },
    //         success: function(res) {
    //           that.setData({
    //             dkcontent: res.data.html,
    //             leassonTilte: res.data.title,
    //             time: res.data.time,
    //             author: res.data.author,
    //             views: res.data.Views,
    //             likeNum: res.data.likeNum,
    //             liked: res.data.liked,
    //             comment: res.data.comment,
    //             commentNum: res.data.commentNum,
    //           })

    // 生成畫布
    // let promise1 = new Promise(function(resolve, reject) {
    //   wx.getImageInfo({
    //     src: res.data.imgUrl,
    //     success: function(res1) {
    //       // console.log(res1)
    //       resolve(res1);
    //     }
    //   })
    // });
    // let promise2 = new Promise(function(resolve, reject) {
    //   wx.getImageInfo({
    //     src: '../../images/qrcode.jpg',
    //     success: function(res1) {
    //       // console.log(res1)
    //       resolve(res1);
    //     }
    //   })
    // });
    // Promise.all([
    //   promise2
    // ]).then(res1 => {
    // console.log(res1)
    // const ctx = wx.createCanvasContext('shareImg')
    //主要就是計算好各個圖文的位置
    // var unit = that.data.screenWidth / 375
    // ctx.setFillStyle('white');
    // ctx.fillRect(0, 0, 600, 880);
    // ctx.drawImage(res1[0].path, 50, 200, 400, 400)
    // ctx.drawImage('../../' + res1[1].path, 350, 610, 160, 160)
    // ctx.drawImage(imgurl, 50, 200, 400, 400)
    // ctx.drawImage(bgImgPath, 350, 610, 160, 160)

    // ctx.setFontSize(28)
    // ctx.setFillStyle('#6F6F6F')
    // ctx.fillText('來自小程序 - 珠三角設代', 30, 660)

    // ctx.setFontSize(30)
    // ctx.setFillStyle('#111111')
    // ctx.fillText('快來圍觀和發佈日誌', 30, 710)

    // ctx.setFontSize(22)
    // ctx.fillText('長按掃碼進入小程序查看', 30, 750)

    // ctx.setFillStyle('#6F6F6F')
    // ctx.fillText('Author:' + res.data.author, 545 / 2, 100)
    // ctx.setTextAlign('center')
    // ctx.setFontSize(24)
    // ctx.setFillStyle('#111111')
    // ctx.fillText(res.data.title, 545 / 2, 50)
    // ctx.fillText(res.data.word, 545 / 2, 160)
    //   ctx.fillText('……', 60, 190)
    //   ctx.stroke()
    //   ctx.draw()
    // })
    //         }
    //       })
    //     }
    //   }
    // })
    // 查看是否授權
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已經授權,可以直接調用 getUserInfo 獲取頭像暱稱
          wx.getUserInfo({
            success: function(res) {
              // console.log(res.userInfo)
            }
          })
        }
      }
    })
  },

  bindGetUserInfo(e) {
    console.log(e.detail.userInfo)
  },

  onShareAppMessage: function() {
    // console.log(this.data.id)
    // var that = this;
    return {
      // desc: '最具人氣的小程序開發聯盟!',
      title: '珠三角設代-分享文件鏈接',
      path: 'pages/pdfview/pdfview?id=' + this.data.Id + '&title=' + this.data.Title+'&actIndex=' + this.data.actIndex
    }
  },

  //點贊切換
  onUpTap: function(event) {
    var that = this;
    var liked = that.data.liked;
    var likeNum = that.data.likeNum; //當前贊數
    // 登錄
    wx.login({
      success: res => {
        // 發送 res.code 到後臺換取 openId, sessionKey, unionId
        if (res.code) {
          //發起網絡請求
          wx.request({
            url: "https://。。。/v1/wx/addwxlike/" + that.data.id,
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            method: "POST",
            data: {
              code: res.code,
              liked: liked,
              app_version: 1.2,
            },
            success: function(res) {
              if (!liked) {
                // views: ++this.data.views,
                likeNum++;
                liked = true;
              } else {
                --likeNum;
                liked = false;
              }
              // break;
              that.setData({
                liked: liked,
                likeNum: likeNum,
              })
              // console.log(that.data.views)
              wx.showToast({
                title: that.data.liked ? "點贊成功" : "點贊取消",
                duration: 1000,
                icon: "sucess",
                make: true
              })
            }
          })
        }
      },
    })
  },

  //收藏切換
  onCollectionTap: function(event) {
    //dbpost對象已在onLoad函數中被保存到了this變量中,無需再次實例化
    var newData = this.dbPost.collect();
    //重新綁定數據,注意,不要將整個newData全部作爲setData的參數,應當有選擇的更新部分數據
    this.setData({
      'post.collectionSataus': newData.collectionStatus,
      'post.collectionNum': newData.collectionNum
    })
    //交互反饋
    wx.showToast({
      title: newData.collectionStatus ? "收藏成功" : "收藏取消",
      duration: 1000,
      icon: "sucess",
      make: true
    })
  },

  // 評論分頁加載
  reviewpage: function(e) {
    var that = this;
    var id = this.data.id;
    console.log('qqqqqq')
    console.log(id)
    console.log('-=-=-=')
    var page = this.data.page;
    wx.request({
      url: link.reviewpage,
      method: 'POST',
      data: {
        id: id,
        page: that.data.page,
        page_size: that.data.page_size
      },
      header: {
        'appid': '。。。GJx',
        'mbcore-access-token': wx.getStorageSync('access_token'),
        'mbcore-auth-token': wx.getStorageSync('auth_token')
      },
      success: function(res) {
        console.log(res)
        console.log('→')
        if (res.data.code == 1) {
          var datas = res.data.result.comments;
          if (res.data.result.more_data == 0) {
            that.setData({
              isShowLoadmore: true,
              isShowNoDatasTips: true,
              endloading: true,
            })

          } else {
            console.log('走到這了')
            that.setData({
              release: that.data.release.concat(datas)
            })
            if (datas.length < that.data.page_size) {
              console.log('已經加載完了')
              that.setData({
                isShowLoadmore: false,
                isShowNoDatasTips: false,
              })
            }
          }
          that.setData({
            page: page + 1
          })
        } else {
          console.log('code等於0啊!')
          that.setData({
            isShowLoadmore: false,
            isShowNoDatasTips: false,
          })
        }
      }
    })
  },

  // 發表評論顯示/隱藏
  bindrelease: function(e) {
    // console.log(e)
    this.setData({
      releaseFocus: false,
      releaseValue: '', //清空輸入框
      focus: true,
    })
    // console.log(this.data.releaseFocus)
  },

  catchhide: function() {
    this.setData({
      releaseFocus: true
    })
    // console.log(this.data.releaseFocus)
  },
  //刪除評論
  binddelete1: function(e) {
    var that = this;
    if (wx.getStorageSync('auth_token')) {
      // 判斷用戶是否登錄
      wx.showModal({
        title: '提示',
        content: '確定撤銷嗎',
        success: function(res) {
          if (res.confirm) {
            console.log('用戶點擊確定')
            wx.request({
              url: link.binddelete,
              method: 'POST',
              header: {
                'appid': '。。。GJx',
                'mbcore-access-token': wx.getStorageSync('access_token'),
                'mbcore-auth-token': wx.getStorageSync('auth_token')
              },
              data: {
                id: e.currentTarget.dataset.id
              },
              success: function(res) {
                console.log(res)
                var dataid = e.currentTarget.dataset.id;
                var index = e.currentTarget.dataset.index
                // 評論總數 
                var conment_length = res.data.result
                var release = that.data.release;
                release.splice(index, 1)
                that.setData({
                  release: release,
                  releaselength: conment_length
                })
              }
            })
          } else if (res.cancel) {
            console.log('用戶點擊取消')
          }
        }
      })
    } else {
      //去註冊登錄
      this.userInfoReadyCallback()
    }
  },

  // 登錄後纔可以發表評論
  // 點擊發表評論
  formSubmit1: function(e) {
    console.log(wx.getStorageSync('auth_token'));
    var that = this;
    var id = this.data.id;
    var textareaValue = e.detail.value.input
    console.log(textareaValue)
    if (wx.getStorageSync('auth_token')) {
      if (e.detail.value.input == '') {
        wx.showToast({
          title: '請輸入內容',
          icon: 'none'
        })
      } else {
        wx.request({
          url: link.formSubmit,
          data: {
            content: textareaValue,
            msgid: id,
          },
          method: 'POST',
          header: {
            'appid': '。。。GJx',
            'mbcore-access-token': wx.getStorageSync('access_token'),
            'mbcore-auth-token': wx.getStorageSync('auth_token')
          },
          success: function(res) {
            console.log(res)
            console.log('-----')
            console.log(res.data.code)
            if (res.data.code == 0) {
              wx.showToast({
                title: '請輸入內容',
                icon: 'none'
              })
            } else {
              //var that = this;
              var textarea_item = {};
              var textareaValue = res.data.result.content;
              var name = res.data.result.username;
              var time = res.data.result.publish_time;
              var avatar = res.data.result.avatar;
              var id = res.data.result.id;
              var like = res.data.result.likes_count;
              var isme = res.data.result.is_me;
              var comments_count = res.data.result.comments_count
              //console.log(release);
              //console.log(that);
              var release = that.data.release;
              textarea_item.content = textareaValue;
              textarea_item.username = name;
              textarea_item.publish_time = time;
              textarea_item.avatar = avatar;
              textarea_item.id = id;
              textarea_item.likes_count = like;
              textarea_item.is_me = isme;
              release.push(textarea_item);
              that.setData({
                release: release,
                releaseFocus: true, //隱藏輸入框
                releaseValue: '', //清空輸入框內容
                releaselength: comments_count //更新頁面發表評論總數
              })
            }
          }
        })
      }
    } else {
      this.userInfoReadyCallback()
    }
  },

  //獲取用戶信息後加上code 去請求auth- token
  userInfoReadyCallback: function(calback) {
    var that = this;
    //console.log(app.globalData.userInfo);
    util.login().then((res) => {
      //console.log("----------");
      return util.getUserAuthRequest(link.authtoken, {
        code: res.code
      })
    }).then(function(res) {
      //如果needBind 是true 則需要本地緩存paramBind驗證手機號時用
      console.log(res.data.result.needBind);
      if (res.data.result.needBind) {
        //爲新用戶,提示去綁定手機號頁面
        var paramBind = wx.getStorageSync('paramBind') || '';
        paramBind = res.data.result.paramBind;
        wx.setStorageSync('paramBind', paramBind);
        wx.showModal({
          title: '提示',
          content: '您尚未登錄,點擊確定去往手機登錄頁面,點擊取消將無法購買',
          success: function(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/bindphone/bindphone'
              })
            } else if (res.cancel) {
              console.log("我點擊了取消按鈕");
              wx.switchTab({
                url: '/pages/index/index'
              })
            }
          }
        });
        // wx.navigateTo({
        //   url: '/pages/bindphone/bindphone'
        // })
      } else {
        //爲老用戶,可以正常登錄,並本地存儲auth_token
        var auth_token = wx.getStorageSync('auth_token') || '';
        auth_token = res.data.result.auth_token;
        wx.setStorageSync('auth_token', auth_token);
        //console.log(wx.getStorageSync('auth_token'));
        if (calback) {
          calback();
        }
      }
    })
  },

  // 添加留言
  formSubmit(e) {
    // console.log(e)
    // console.log(this.data.id)
    var that = this
    if (e.detail.value.input == '') {
      // if (this.data.releaseValue == '') {
      wx.showToast({
        title: '請留言',
      })
      return false;
    }
    var list = this.data.comment;
    // 必須是在用戶已經授權的情況下調用
    // 獲取用戶信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已經授權,可以直接調用 getUserInfo 獲取頭像暱稱,不會彈框
          // wx.getUserInfo({
          // success: res => {
          wx.getUserInfo({
            success: function(res) {
              var userInfo = res.userInfo
              var nickName = userInfo.nickName
              var avatarUrl = userInfo.avatarUrl
              var gender = userInfo.gender //性別 0:未知、1:男、2:女
              var province = userInfo.province
              var city = userInfo.city
              var country = userInfo.country
              // console.log(e.detail.value.input)
              // console.log(this.data)
              var a = list ? list : []
              // 調用函數時,傳入new Date()參數,返回值是日期和時間  
              var time = util.formatTime(new Date());

              // 登錄
              wx.login({
                success: res => {
                  // 發送 res.code 到後臺換取 openId, sessionKey, unionId
                  if (res.code) {
                    //發起網絡請求
                    wx.request({
                      url: "https://。。。/v1/wx/addwxrelease/" + that.data.id,
                      header: {
                        "Content-Type": "application/x-www-form-urlencoded"
                      },
                      method: "POST",
                      data: {
                        code: res.code,
                        content: e.detail.value.input,
                        username: nickName,
                        publish_time: time,
                        avatar: avatarUrl,
                        app_version: 1.2,
                      },
                      // header: {
                      //   'appid': '。。。GJx',
                      //   'mbcore-access-token': wx.getStorageSync('access_token'),
                      //   'mbcore-auth-token': wx.getStorageSync('auth_token')
                      // },
                      success: function(res) {
                        // 再通過setData更改Page()裏面的data,動態更新頁面的數據  
                        a.push({
                          content: e.detail.value.input, //this.data.releaseValue
                          username: nickName,
                          is_me: true,
                          publish_time: time,
                          // likes_count: 5,
                          avatar: avatarUrl,
                        })
                        wx.setStorage({
                          key: 'info',
                          data: a,
                        })
                        that.setData({
                          comment: a,
                          releaseValue: '',
                          releaseFocus: true, //隱藏輸入框
                          // releaselength: comments_count //更新頁面發表評論總數
                        })
                        // console.log(avatarUrl)
                      }
                    })
                  }
                }
              })
            },
          })
        }
      }
    })
  },

  changeinputVal(e) {
    console.log(e.detail)
    this.setData({
      releaseValue: e.detail.value
    })
  },

  // 刪除留言
  binddelete(e) {
    var that = this
    var index = e.currentTarget.dataset.index //e.target.dataset.id;
    // console.log(e)
    var comment = that.data.comment
    wx.showModal({
      title: '提示',
      content: '是否刪除該條數據',
      success: function(res) {
        if (res.confirm) {

          //發起網絡請求
          wx.request({
            url: "https://。。。/v1/wx/deletewxrelease/" + e.currentTarget.dataset.id,
            method: "POST",
            success: function(res) {
              comment.splice(index, 1);
              that.setData({
                comment: comment
              })
              // console.log(that.data.comment)
              wx.showToast({
                title: '刪除成功',
              })
            }
          })
        }
      }
    })
  },

  /**
   * 生成分享圖
   */
  share: function() {
    var that = this
    //獲取用戶設備信息設備像素比
    // wx.getSystemInfo({
    //   success: res => {
    //     that.setData({
    //       pixelRatio: res.pixelRatio
    //     })
    //     console.log(that.data.pixelRatio)
    //   }
    // })
    // 本質上就是生成一個更大的圖片,因爲手機的屏幕設備的像素比現在一般都是超過2的。實際上我們只需要在使用wx.canvasToTempFilePath的時候,設置參數destWidth和destHeight(輸出的寬度和高度)爲width和height的2倍以上即可。
    wx.showLoading({
      title: '努力生成中...'
    })
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 545,
      height: 771,
      destWidth: 545 * 2,
      destHeight: 771 * 2,
      canvasId: 'shareImg',
      success: function(res) {
        // console.log(res.tempFilePath);
        that.setData({
          prurl: res.tempFilePath,
          hidden: false
        })
        wx.hideLoading()
      },
      fail: function(res) {
        console.log(res)
      }
    })
  },

  /**
   * 保存到相冊
   */
  save: function() {
    var that = this
    //生產環境時 記得這裏要加入獲取相冊授權的代碼
    wx.saveImageToPhotosAlbum({
      filePath: that.data.prurl,
      success(res) {
        wx.showModal({
          content: '圖片已保存到相冊,趕緊曬一下吧~',
          showCancel: false,
          confirmText: '好噠',
          confirmColor: '#72B9C3',
          success: function(res) {
            if (res.confirm) {
              // console.log('用戶點擊確定');
              that.setData({
                hidden: true
              })
            }
          }
        })
      }
    })
  },

  //預覽pdf文件
  downloadFile: function(e) {
    console.log(e)
    var that = this;
    // console.log(that.data.actIndex)
    if (that.data.actIndex=='standard') {
      that.setData({
        downloadurl: 'https://。。。/v1/wx/wxstandardpdf/' + e.currentTarget.dataset.id,
      });
    } else {
      that.setData({
        downloadurl: 'https://。。。/v1/wx/wxpdf/' + e.currentTarget.dataset.id,
      });
    };

    wx.downloadFile({
      url: that.data.downloadurl,
      success: function(res) {
        console.log(res)
        const filePath = res.tempFilePath //返回的文件臨時地址,用於後面打開本地預覽所用
        wx.openDocument({
          filePath: filePath,
          fileType: 'pdf',
          success: function(res) {
            console.log('打開成功');
          },
          fail: function(res) {
            console.log(res);
          }
        })
      },
      fail: function(res) {
        console.log(res);
      }
    })
  }
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章