小程序开发系列(九)文档下载与预览

在小程序中,有时数据中含有一些必要的文档需要下载,当我们与后端交互得到了文档的URL后,无法直接预览,需要将其下载,然后再预览。

UI代码如下

 <view bindtap='previewFile' data-url='{
  {doc.Url}}'>
      <label>文档:</label>{
  {doc.Name}}</view>
其中doc是后端返回的数据,内部包含了Url和Name两个字段。同时在View中绑定了一个下载文件的事件。

 previewFile: function (event) {
    var that = this;
    var url = event.currentTarget.dataset.url;
    if (url === undefined || url === null || url.length <= 0) {
      wx.showToast({
        title: 'URL为空',
      })
      return;
    }

    var index1 = url.lastIndexOf(".");
    var suffixName = url.substring(index1 + 1, url.length);//后缀名 
    if (suffixName === undefined || suffixName === null || suffixName.length <= 0) {
      wx.showTo
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
⼩程序下载⽂件并预览 需求分析 最近优化了个原先写过的需求,回头复习复习⼩程序的 API 是这样的,我需要下载⼀个⽂件并打开此⽂件 优化:记录是否被下载过,如果下载过就直接打开 获取⽂件下载链接,打开⽂件 wx.downloadFile({ url: `${pic.meetingUrl}/weixin/noticeStart/downLoad/${this.selectItem.recordId}`, // 下载资源的 url success: (res) => { wx.openDocument({ filePath: res.tempFilePath, // ⽂件路径,可通过 downloadFile 获得, fileType: 'pdf', // 写下载后的⽂件的格式,这⾥距离是pdf success: (res) => { }, fail: (error) => { }, }); }, fail: () => {}, complete: () => {}, }); 优化 思路:保存下载后的⽂件,保存其路径到本地缓存,然后下次打开的时候判断⼀下本地缓存⾥是否有,如果有就打开,本地缓存没有的话, 就先下载在打开。 const that = this; const cacheFilePath = wx.getStorageSync( `filePath-${this.selectItem.recordId}` ); // 先判断这个⽂件是否下载过 // 如果下载过,尝试通过缓存,打开⽂件 // 否则就要下载下载成功后保存本地缓存(临时路径信息),命名规则为 filePath + recordId if (cacheFilePath) { wx.openDocument({ filePath: cacheFilePath, //⽂件路径,可通过 downFile 获得, fileType: this.selectItem.fileType, // 获取⽂件格式 success: (res) => { }, fail: (error) => { }, }); } else { wx.showLoading({ title: "下载中", mask: true, }); wx.downloadFile({ url: `${pic.meetingUrl}/weixin/noticeStart/downLoad/${this.selectItem.recordId}`, // 下载资源的 url success: (res) => { // 隐藏 loading wx.hideLoading(); // 下载成功后,保存⽂件路径到本地缓存 wx.setStorageSync( `filePath-${this.selectItem.recordId}`, `${res.tempFilePath}` ); // 尝试打开下载后的⽂件 wx.openDocument({ filePath: res.tempFilePath, //⽂件路径,可通过 downFile 获得, fileType: this.selectItem.fileType, // 获取⽂件格式 success: (res) => { }, fail: (error) => { }, }); }, fail: () => {}, complete: () => {}, }); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值