feat(system): write to system media for tack photo

This commit is contained in:
Timi
2026-11-18 14:08:47 +08:00
parent 635192eae1
commit 60cadff951
8 changed files with 289 additions and 1 deletions
@@ -53,6 +53,8 @@ import type {
import type { PhotoItem } from "@/types/Photo.ts";
import { getAttachmentReadURL } from "@/utils/attachment.ts";
import { Message } from "@/utils/message.ts";
import { saveToAlbum } from "@/utils/mediaSaver";
import { useSettingStore } from "@/store/settingStore";
defineOptions({
inheritAttrs: false
@@ -76,6 +78,8 @@ const props = withDefaults(defineProps<Props>(), {
required: false
});
const settingStore = useSettingStore();
const emit = defineEmits<{
"update:items": [items: PhotoItem[]];
select: [selection: AttachmentSelectorSelection];
@@ -88,6 +92,13 @@ const isBusy = computed(() => props.busy || isUploading.value);
const attachmentItems = computed(() => props.items.map(toAttachmentSelectorItem));
async function handleSelect(selection: AttachmentSelectorSelection): Promise<void> {
// 直接拍摄的媒体额外存一份到系统相册,可在「应用设置」里关掉;失败不阻塞上传
if (settingStore.albumSave && selection.input.capture && selection.files.length) {
const mediaType: "image" | "video" = selection.input.accept.toLowerCase().includes("video") ? "video" : "image";
for (const file of selection.files) {
void saveToAlbum(file, mediaType).catch(() => Message.warning("保存到系统相册失败"));
}
}
if (!props.upload) {
emit("select", selection);
return;
+7
View File
@@ -25,6 +25,13 @@
</template>
</t-cell>
</t-cell-group>
<t-cell-group title="照片" theme="card" v-entrance-transition>
<t-cell title="拍照后存入相册">
<template #right-icon>
<t-switch :model-value="settingStore.albumSave" @change="value => settingStore.setAlbumSave(value === true)" />
</template>
</t-cell>
</t-cell-group>
<t-cell-group title="声音" theme="card" v-entrance-transition>
<t-cell title="扫码成功">
<template #right-icon>
+11
View File
@@ -10,6 +10,7 @@ export interface SoundSetting {
type SoundType = "scanSuccess" | "registerSuccess";
const SOUND_STORAGE_KEY = "gao-customer-h5:sound";
const ALBUM_SAVE_STORAGE_KEY = "gao-customer-h5:album-save";
const soundUrlMap: Record<SoundType, string> = {
scanSuccess: scanSuccessSoundUrl,
registerSuccess: registrationSuccessSoundUrl
@@ -48,6 +49,8 @@ function readStoredSoundSetting(): SoundSetting {
export const useSettingStore = defineStore("setting", () => {
const sound = ref<SoundSetting>(readStoredSoundSetting());
/** 拍照后是否额外存一份到系统相册,默认开启 */
const albumSave = ref(localStorage.getItem(ALBUM_SAVE_STORAGE_KEY) !== "0");
const soundPlayerMap = shallowRef<Record<SoundType, HTMLAudioElement> | null>(null);
const audioContext = shallowRef<AudioContext | null>(null);
const scanSuccessBuffer = shallowRef<AudioBuffer | null>(null);
@@ -64,6 +67,12 @@ export const useSettingStore = defineStore("setting", () => {
applySoundVolume();
}
/** 开关相册副本,只影响后续拍摄,已保存的文件不动 */
function setAlbumSave(value: boolean): void {
albumSave.value = value;
localStorage.setItem(ALBUM_SAVE_STORAGE_KEY, value ? "1" : "0");
}
function loadSoundPlayers(): void {
if (soundPlayerMap.value) {
return;
@@ -223,7 +232,9 @@ export const useSettingStore = defineStore("setting", () => {
return {
sound,
albumSave,
setSound,
setAlbumSave,
loadSoundPlayers,
unlockSoundPlayers,
playScanSuccessSound,
+68
View File
@@ -0,0 +1,68 @@
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);
}