tme-webview-uploader
v1.0.10
Published
A simple file uploader for WeChat Mini Program
Maintainers
Readme
tme-webview-uploader
一个用于 H5 和微信小程序 webview 之间文件上传交互的工具包。
安装
npm install tme-webview-uploader使用方法
1. 小程序接入方法
1.1 在 pages 声明 webview 页面和上传页面
在 app.json 中声明页面路径:
{
"pages": [
// ... 其他页面
"pages/webview/index",
"pages/uploadTransferPage/index"
]
}1.2 在 webview 页面内进行封装
import { withUploader } from "tme-webview-uploader";
// webview 原逻辑
const Webview = () => {
// some logic
};
const opt = {
uploadPagePath: "pages/uploadTransferPage/index",
};
const UploaderWebview = withUploader(Webview, opt);
export default UploaderWebview;1.3 新建 pages/uploadTransferPage/index
import { createUploaderTransferPage } from "tme-webview-uploader";
type opt = {
getUploadConfig: any;
getResponse: any;
// ... 其他参数
};
export default createUploaderTransferPage(opt);2. H5 使用方式
import { tmeWebviewUploader } from "tme-webview-uploader";
// 类型定义
type UploadFile = {
count?: number; // 单个文件的数量
size?: number; // 文件的大小
type?: "all" | "image" | "file"; // 限制文件类型,如 type='all',则不限制文件类型
extension?: string[]; // 文件限制
webviewPath?: string; // 小程序webview页面路径
topic?: string; // 上传主题
username?: string; // 用户名
};
// 接口调用
const uploads = await tmeWebviewUploader({
count: 5, // 最大上传数量
size: 10 * 1024 * 1024, // 10M
type: "image", // 文件类型
extension: [".jpg"], // 限制文件类型
topic: "上传身份证照片",
username: "张三",
});API 文档
tmeWebviewUploader
H5 端调用小程序上传功能的主要接口。
参数 (UploadFile)
| 参数 | 类型 | 必填 | 默认值 | 说明 | | ----------- | -------------------------- | ---- | -------------------------------- | ------------------------ | | count | number | 否 | 10 | 最大上传文件数量 | | size | number | 否 | 40MB | 单个文件最大大小(字节) | | type | 'all' | 'image' | 'file' | 否 | 'all' | 文件类型限制 | | extension | string[] | 否 | [] | 允许的文件扩展名数组 | | webviewPath | string | 否 | 'pages/uploadTransferPage/index' | 小程序上传页面路径 | | topic | string | 否 | '文件上传' | 上传页面标题 | | username | string | 否 | '用户' | 用户名显示 |
返回值 (UploadResult)
interface UploadResult {
code?: 0 | 1; // 0 成功, 1 取消上传
data?: Array<{
cosUrl: string; // cos链接
type: string; // 文件类型
size: number; // 文件大小
name: string; // 文件名称
}>;
}使用示例
// 身份证上传
const result = await tmeWebviewUploader({
count: 1,
size: 5 * 1024 * 1024, // 5MB
extension: ["jpg", "jpeg", "png"],
topic: "上传身份证照片",
username: "张三",
});
// 多文件上传
const result = await tmeWebviewUploader({
count: 5,
size: 10 * 1024 * 1024, // 10MB
type: "file",
extension: ["pdf", "doc", "docx"],
topic: "上传文档资料",
username: "李四",
});withUploader
用于增强 WebView 组件的高阶组件。
参数
| 参数 | 类型 | 必填 | 说明 | | --------- | ------------------- | ---- | ----------------------- | | Component | React.ComponentType | 是 | 需要增强的 WebView 组件 | | options | WithUploaderOptions | 是 | 配置选项 |
WithUploaderOptions
interface WithUploaderOptions {
uploadPagePath?: string; // 上传页面路径
[key: string]: any; // 其他配置选项
}使用示例
import { withUploader } from "tme-webview-uploader";
const MyWebView = () => {
return <web-view src="" />;
};
const EnhancedWebView = withUploader(MyWebView, {
uploadPagePath: "pages/upload/index",
});
export default EnhancedWebView;createUploaderTransferPage
创建小程序端上传页面组件的工厂函数。
参数 (UploaderTransferPageOptions)
interface UploaderTransferPageOptions {
getUploadConfig: () => Promise<{
url: string;
header?: Record<string, any>;
formData?: Record<string, any>;
}>;
getResponse: (response: any) => Promise<any>;
[key: string]: any;
}使用示例
这里用户可以传入对应的 cos 链接等信息以及期望的数据格式
import { createUploaderTransferPage } from "tme-webview-uploader";
const uploadPageOptions = {
getUploadConfig: async () => ({
url: "https://supersonic.test.tmeoa.com/cp-platform/api/batch/task/file/upload",
header: {
Authorization: "Bearer token",
"Content-Type": "multipart/form-data",
},
}),
getResponse: async (response) => {
const data = JSON.parse(response.data);
return {
cosUrl: data.fileUrl,
fileName: data.originalName,
fileId: data.fileId,
};
},
};
export default createUploaderTransferPage(uploadPageOptions);uploadUtils
工具函数集合。
方法
checkNetwork()
检查网络状态,非 WiFi 网络会提示用户确认。
import { uploadUtils } from "tme-webview-uploader";
try {
await uploadUtils.checkNetwork();
console.log("网络检查通过");
} catch (error) {
console.log("用户取消上传");
}formatFileSize(bytes: number): string
格式化文件大小显示。
uploadUtils.formatFileSize(1024); // "1 KB"
uploadUtils.formatFileSize(1024 * 1024); // "1 MB"
uploadUtils.formatFileSize(1024 * 1024 * 1.5); // "1.5 MB"validateFileType(fileName: string, allowedExtensions: string[]): boolean
验证文件类型是否在允许的扩展名列表中。
uploadUtils.validateFileType("document.pdf", [".pdf", ".doc"]); // true
uploadUtils.validateFileType("image.jpg", [".png", ".gif"]); // false功能特性
- ✅ H5 与小程序无缝对接 - 通过 webview 实现跨端文件上传
- ✅ 多种文件类型支持 - 支持图片、文档等多种文件格式
- ✅ 文件大小限制 - 可配置单个文件最大大小
- ✅ 文件类型验证 - 支持按扩展名限制文件类型
- ✅ 上传进度显示 - 实时显示文件上传进度
- ✅ 网络状态检查 - 非 WiFi 环境自动提示用户确认
- ✅ 错误处理 - 完善的错误处理和用户提示
- ✅ TypeScript 支持 - 完整的类型定义
工作流程
- H5 页面调用 - 用户在 H5 页面点击上传按钮
- 参数传递 - 调用
tmeWebviewUploader传递上传配置 - 页面跳转 - 自动跳转到小程序上传页面
- 文件选择 - 用户在小程序中选择文件
- 文件验证 - 自动验证文件大小和类型
- 网络检查 - 检查网络状态并提示用户
- 文件上传 - 上传文件到指定服务器
- 进度显示 - 实时显示上传进度
- 结果返回 - 上传完成后返回结果到 H5 页面
注意事项
- 环境要求 - 必须在微信小程序的 webview 中使用,自动适配 H5 和小程序环境
- webview 配置 - 确保小程序 webview 页面监听了
onMessage事件(见上方示例) - 网络环境 - 建议在 WiFi 环境下进行文件上传,避免消耗用户流量
- 文件大小 - 根据实际需求合理设置文件大小限制
- 文件类型 - 根据业务需求配置允许的文件扩展名
- 服务器配置 - 确保上传服务器支持大文件上传
- 错误处理 - 建议在调用接口时添加 try-catch 错误处理
更新日志
v1.0.3
- 修复:增强 wx.miniProgram 检测逻辑,支持延迟初始化场景
- 增强:添加环境检测调试日志,方便排查问题
- 优化:等待 wx.miniProgram 初始化,最多等待 2 秒
v1.0.2
- 修复:修复在 webview 的 H5 页面中
wx is not defined的问题 - 增强:自动检测小程序环境和 webview 环境,无需手动桥接
- 优化:使用 localStorage 在 webview 环境中存储配置,避免直接调用 wx API
v1.0.1
- 优化依赖配置,将
@tarojs/components调整为 peerDependency
v1.0.0
- 初始版本发布
- 支持 H5 与小程序文件上传交互
- 提供完整的 TypeScript 类型定义
- 包含文件验证、进度显示、网络检查等功能
许可证
MIT License
