uni-app 微信小程序 支付宝小程序(alipay) 百度小程序(baidu),预览pdf(链接和base64) 及下载(仅微信),window.open uni.downloadFile

废话不多说直接上代码吧

之前搜了一大堆有的没的,最终还是小伙伴巴拉文档一起找到的方案(离不开小伙伴的帮助,自己总容易陷入死局,在此鸣谢 疾风李青!);

想起个事:一定要给这些路径的域名配到相应的开发管理上,其他平台不过多赘述了
uni-app 微信小程序 支付宝小程序(alipay) 百度小程序(baidu),预览pdf(链接和base64) 及下载(仅微信),window.open uni.downloadFile_第1张图片

首先是预览,由于我这里是uni-app框架开发三端,所以展示内容开头以uni为主:
如果你的dpf是链接形式 形如:https:// ,那么下面方案适合你(该方案,是小程序中的window.open的实现。)

支付宝不同机型 调用uni.downloadFile 发现会发现有多种形式的文件路径,因此条件编译一下(纯他么坑爹)

const times = new Date().getTime();
let userPath = '';
// #ifdef MP-ALIPAY
userPath = my.env.USER_DATA_PATH;
// #endif
// #ifdef MP-WEIXIN
userPath = wx.env.USER_DATA_PATH;
// #endif
// #ifdef MP-BAIDU
userPath = swan.env.USER_DATA_PATH;
// #endif

let filePath = userPath + '/' + times + '.pdf';

export default (url) => {
  uni.downloadFile({ // 下载
    url, // 服务器上的pdf地址
    filePath,
    success: (res) => {
      let openDocumentPath = filePath;
      // #ifdef MP-ALIPAY
      openDocumentPath = res.tempFilePath || res.filePath || filePath;
      // #endif
      uni.openDocument({
        fileType: 'pdf',
        showMenu: true,
        filePath: openDocumentPath,
        success: () => {
          console.log('打开PDF成功')
        },
        fail: (err) => {
          uni.showToast({
            title: '打开文档失败,请重试!'
          })
        }
      })
    }
  })
}

如果你的链接是base64,那么这个方案适合你

const times = new Date().getTime();
let userPath = '';
// #ifdef MP-ALIPAY
userPath = my.env.USER_DATA_PATH;
// #endif
// #ifdef MP-WEIXIN
userPath = wx.env.USER_DATA_PATH;
// #endif
// #ifdef MP-BAIDU
userPath = swan.env.USER_DATA_PATH;
// #endif

let filePath = userPath + '/' + times + '.pdf';

export default (data) => {
  const fileSystemManager = uni.getFileSystemManager(); 
  fileSystemManager.writeFile({
    //保存本地临时路径
    filePath,
    data,
    encoding: 'base64',
    success: (res) => {
      uni.openDocument({
        fileType: 'pdf',
        showMenu: true,
        filePath,
        success: function (res) {
          console.log('打开PDF成功')
        },
        fail(err) {
          uni.showToast({
            title: '打开文档失败,请重试!'
          })
        }
      })
    }
  })
}

总结:
主要思路还是通过不同的api将文件先下载到小程序存储,通过uni.openDocument去打开,

  1. 配置相应服务器域名。
  2. 使用对应小程序api预览。

下载:
仅微信安卓端可实现,
uni.openDocument 打开 showMenu: true,
其实就是微信预览的时候,开启menu,通过右上角的三个点点击后保存到手机。

看到其他大牛给到的方案,都不是很完美,贴个链接吧。

微信小程序下载文件,保存文件功能总结

  1. 通过base64或pdf链接 转 png后,再fileSystemManager.saveFile API保存文件为图片格式;
    下载,完事让用户自己改后缀。

  2. 先使用下载文件api把文件下载下来,再使用wx.openDocument() 打开文件里面加上showMenu字段,然后就可以看到在打开的文件右上角出现了,
    ​ ios表现:ios点击之后会有发送给朋友的选项,选择分享给朋友之后就可以把文件直接发送给对方了,然后你就可以在聊天记录里面拿到这个文件;

这两种方式 都不是很完美,所以 小程序端暂时不建议提供下载功能,
除非给个链接 让用户沾出去从浏览器下载。

你可能感兴趣的:(小程序,微信小程序,微信)