小程序打开文件(文件流、地址链接)封装

一、核心 API:wx.openDocument

这是小程序中用于打开非图片/视频文件的官方API,主要用于预览办公文档格式。 支持的文件类型:

文件类型 fileType 值 支持情况
PDF 文件 pdf ✅ 广泛支持
Word 文档 doc, docx ✅ 大部分支持
Excel 表格 xls, xlsx ✅ 大部分支持
PPT 演示稿 ppt, pptx ✅ 大部分支持
文本文件 txt ✅ 支持
其他格式 不指定或 null ⚠️ 依赖系统

基本用法

js 复制代码
wx.openDocument({
  filePath: '', // 文件临时路径或本地路径
  fileType: 'pdf', // 文件类型,可选
  success: (res) => {
    console.log('打开文档成功');
  },
  fail: (err) => {
    console.error('打开文档失败:', err);
  }
})
js 复制代码
// 打开后端返回的二进制流文件
export function openFileStream(fileName = 'HN', fileType = 'pdf', params = {}, apiUrl = '') {
    return new Promise((resolve, reject) => {
        wx.showLoading({
            title: '加载文件中...',
            mask: true
        });
        wx.request({
            url: apiUrl,
            method: 'POST',
            data: params,
            responseType: 'arraybuffer',  //**注意设置
            header: {
                'Content-Type': 'application/json',
                'token': wx.getStorageSync('token'),
            },
            success: async (res) => {
                wx.hideLoading();
                if (res.statusCode === 200 && res.data) {
                    try {
                        const fs = wx.getFileSystemManager();
                        const tempFilePath = `${wx.env.USER_DATA_PATH}/temp_${fileName}.${fileType}`;

                        // 写入文件
                        fs.writeFile({
                            filePath: tempFilePath,
                            data: res.data,
                            encoding: 'binary',
                            success: () => {
                                // 打开文档
                                wx.openDocument({
                                    filePath: tempFilePath,
                                    success: resolve,
                                    fail: (err) => {
                                        reject(
                                            wx.showToast({
                                                title: '文件打开失败...',
                                                icon: 'none',
                                                duration: 3000,
                                            })
                                        );
                                    }
                                });
                            },
                            fail: (err) => {
                                reject(new Error('文件保存失败: ' + err.errMsg));
                            }
                        });
                    } catch (error) {
                        reject(error);
                    }
                } else {
                    reject(
                        wx.showToast({
                            title: '接口请求失败...',
                            icon: 'none',
                            duration: 3000,
                        })
                    )
                }
            },
            fail: (err) => {
                wx.hideLoading();
                reject(new Error('网络请求失败: ' + err.errMsg));
            }
        });
    });
}

//打开后端返回的地址链接
export function openFileUrl(url = '') {
    return new Promise((resolve, reject) => {
        wx.showLoading({
            title: '加载文件中...',
            mask: true
        });
        if (url) {
            wx.openDocument({
                filePath: url,
                success: resolve,
                fail: (err) => {
                    reject(new Error('文件打开失败: ' + err.errMsg));
                }
            });
        } else {
            wx.hideLoading();
            reject(new Error('未提供有效的URL'));
        }
    });
}
文件大小限制:
  • 建议单文件不超过 10MB
  • 过大文件可能导致打开失败或内存问题
小程序打开文件的核心流程:
  1. 获取文件 → 下载或读取本地文件
  2. 验证文件 → 检查文件是否存在和有效
  3. 打开文档 → 使用 wx.openDocument 打开
  4. 错误处理 → 提供友好的错误提示
相关推荐
万少8 小时前
给 DeepSeek Harness 装个"应用商店":一条命令,595 个插件随你逛
前端·javascript·后端
波波0078 小时前
C# 15 重磅新特性: 带标签 break 与 continue:重新定义嵌套循环控制流
服务器·前端·c#
Brown.alexis9 小时前
es6知识点1-自备使用
前端·ecmascript·es6
小爬的老粉丝10 小时前
JavaScript 纯前端预览 WPS:先识别容器,再路由解析器
前端·javascript·wps
计算机魔术师10 小时前
新兴多智能体系统的模式与问题
前端
用户0595401744611 小时前
AI Agent 上下文污染踩坑实录:用 pytest + Redis 揪出 3 类记忆串号 bug,排查 6 小时
前端·css
满栀58511 小时前
状态管理:Redux、Vuex、Pinia 核心区别
前端·javascript·typescript
一拳不是超人12 小时前
DeepSeek Harness 为什么敢说"一切皆插件"?拆透 Cordis 引擎的五大核心机制
前端·人工智能·agent
IT_陈寒12 小时前
Python的GIL让我多写了500行代码
前端·人工智能·后端
风骏时光牛马12 小时前
AI智能体能力调度微服务
前端