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

一、核心 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. 错误处理 → 提供友好的错误提示
相关推荐
橙序员小站2 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名4 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫4 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊4 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter4 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折5 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_5 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
Angelial5 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js
jiayu5 小时前
Angular学习笔记24:Angular 响应式表单 FormArray 与 FormGroup 相互嵌套
前端
jiayu5 小时前
Angular6学习笔记13:HTTP(3)
前端