小程序在线阅读文档

下载并预览文档:

  1.通过 downloadFile方法,下载成功,

  2.然后接着调用openDocument打开文档

openDocument新开页面打开文档,支持合法格式:DOC, XLS, PPT, PDF, DOCX, XLSX, PPTX。

  小程序文档:https://developers.weixin.qq.com/miniprogram/dev/api/wx.openDocument.html

  这里模拟列表数据查看文档。

 <block wx:for="{{list}}" >
  
  <view class='background'>
     <view  data-url="{{item.url}}"  catchtap='downloadFile' class='color'>{{item.title}}</view>

    <view>
      <text class='times'>上传时间:</text> 
      <text>{{item.time}}</text>
    </view>
     
  </view>

  </block>
Page({

  /**
   * 页面的初始数据
   */
  data: {

    list:[
      {
        title:'前端学习正品',
        url:'http://*************.pdf',
        time:"2019.1.10"
      },
       {
        title: '小程序最全项目',
         url: 'http://***************.pdf',
         time: "2019.1.10"
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
  },

  /**
  * 下载文件并预览
  */
  downloadFile: function (e) {
    let url = e.currentTarget.dataset.url;
    console.log("*********正在获取文件名****" + url)
    wx.downloadFile({
      url: url,//这里的url是通过模拟数据里面的数组对象,列表形式方式
      //url:"http://*************.pdf", //这样的固定文档值,
      success: function (res) {
        const filePath = res.tempFilePath; //返回的文件临时地址,用于后面打开本地预览所用
        console.log("文件"+filePath);
        wx.openDocument({
          filePath: filePath, 
          success: function (res) {
            console.log('您成功打开文档,欢迎阅读')
          },
          fail: function (res) {
            console.log(res);
            console.log("错误")
          },
          
        })
      },
      fail: function (res) {
        console.log('文件下载失败');
      },
      
    })
  },

 
})            

 

这样就完成了在线阅读文档