Files
gao-customer-h5/src/utils/mediaSaver.ts
T

69 lines
2.5 KiB
TypeScript

import { Capacitor, registerPlugin } from "@capacitor/core";
interface MediaSaverPlugin {
begin(options: { fileName: string; mimeType: string; mediaType: "image" | "video" }): Promise<{ id: string }>;
append(options: { id: string; data: string }): Promise<void>;
finish(options: { id: string }): Promise<void>;
cancel(options: { id: string }): Promise<void>;
}
const MediaSaver = registerPlugin<MediaSaverPlugin>("MediaSaver");
/** 分块大小,base64 后约 683KB,避免把整个视频一次性塞进桥接调用 */
const CHUNK_SIZE = 512 * 1024;
/** 相册文件名只允许安全字符 */
const SAFE_NAME = /^[\w.-]{1,120}$/;
/** 当前外壳是否具备写相册的能力 */
export function supportsAlbumSave(): boolean {
return Capacitor.isPluginAvailable("MediaSaver");
}
/**
* 把直接拍摄得到的媒体写进系统相册
*
* 写的是 MediaStore 自己的记录,Android 10 起不需要存储权限。
* 失败由调用方决定怎么处理——相册保存是增强能力,绝不能影响上传。
*
* @param file 拍摄产物
* @param mediaType 媒体类型,决定落到 DCIM 还是视频集合
*/
export async function saveToAlbum(file: File, mediaType: "image" | "video"): Promise<void> {
if (!supportsAlbumSave() || !file.size) {
return;
}
const { id } = await MediaSaver.begin({
fileName: buildFileName(file, mediaType),
mimeType: file.type || (mediaType === "video" ? "video/mp4" : "image/jpeg"),
mediaType
});
try {
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
const chunk = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();
await MediaSaver.append({ id, data: toBase64(chunk) });
}
await MediaSaver.finish({ id });
} catch (error) {
await MediaSaver.cancel({ id }).catch(() => undefined);
throw error;
}
}
/** 生成相册里的显示名,拿不到可用原名时用时间戳兜底 */
function buildFileName(file: File, mediaType: "image" | "video"): string {
const suffix = mediaType === "video" ? "mp4" : "jpg";
const name = file.name && SAFE_NAME.test(file.name) ? file.name : `IMG_${Date.now()}.${suffix}`;
return name.includes(".") ? name : `${name}.${suffix}`;
}
/** ArrayBuffer 转 base64,分段拼接避免超长参数撑爆调用栈 */
function toBase64(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer);
let binary = "";
for (let index = 0; index < bytes.length; index += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
}
return window.btoa(binary);
}