一、核心 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
- 过大文件可能导致打开失败或内存问题
小程序打开文件的核心流程:
- 获取文件 → 下载或读取本地文件
- 验证文件 → 检查文件是否存在和有效
- 打开文档 → 使用
wx.openDocument
打开 - 错误处理 → 提供友好的错误提示