uni-app微信小程序二进制文件流预览功能实现(ossid下载版)

需求

在线预览doc/docx/xls/xlsx/ppt/txt/pdf 的文件和图片

思路

  1. 将后台返回的二进制流,写入微信的文件管理器。
  2. 打开文件

苹果、安卓真机均可预览文件

1.点击文字预览

<view @tap="handleFileList(item, index)">点击文字预览</view>

2.将后台返回的二进制流,写入微信的文件管理器(getDownload此处用的是封装好的api接口,也可以直接wx.request({})直接在这里请求)

<script>
export default {
 methods: {
    //预览方法
    handleFileList(item, index) {
      let ossId = item.ossid;//文件ossid
      let fileName = item.name;//文件名称
      uni.showLoading({
        title: "正在打开",
      });
      getDownload(ossId)
        .then((response) => {
          const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`;//获取临时下载存储路径
          try {
            wx.getFileSystemManager().writeFileSync(
              filePath,
              response,
              "binary"
            );//获取全局唯一的文件管理器并写入
            uni.hideLoading();
            // 打开文件
            uni.openDocument({
              filePath: filePath,//路径
              showMenu: true,
              success: function (res) {
                console.log("打开文档成功");
              },
              fail: function (err) {
                uni.showToast({
                  icon: "none",
                  title: "打开文档失败",
                });
                console.error("打开文档失败", err);
              },
            });
          } catch (e) {
            console.error("写入文件时发生错误", e);
            uni.hideLoading();
          }
        })
        .catch((err) => {
          console.error("获取文件流数据失败", err);
          uni.hideLoading();
        });
    }
  }
}
</script>

3.api.js

import config from "../config/config.js";
const request = config.request;

// 获取文件下载地址
export function getDownload(ids) {
	return request({
		url: `${ip}/resource/oss/download/` + ids,
		method: 'GET',
		responseType: "arraybuffer"
	})
}

 注:真机调试也是OK的。

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值