gongxiangp2/lib/material-protected-storage.ts

36 lines
1.2 KiB
TypeScript

import { mkdir, writeFile, copyFile, stat } from 'fs/promises'
import path from 'path'
import { resolveStoredUploadPath } from '@/lib/upload-paths'
function protectedDisplayPath(materialId: string, fileName: string) {
return path.posix.join('uploads', 'materials', materialId, 'protected-display', fileName.replace(/\\/g, '/'))
}
export async function saveProtectedMaterialDisplay(
materialId: string,
fileName: string,
buffer: Buffer,
): Promise<string> {
const storedPath = protectedDisplayPath(materialId, fileName)
const destination = resolveStoredUploadPath(storedPath)
await mkdir(path.dirname(destination), { recursive: true })
await writeFile(destination, buffer)
return storedPath
}
export async function saveProtectedMaterialDisplayFile(
materialId: string,
fileName: string,
source: string,
expectedSize?: number,
): Promise<string> {
const storedPath = protectedDisplayPath(materialId, fileName)
const destination = resolveStoredUploadPath(storedPath)
await mkdir(path.dirname(destination), { recursive: true })
await copyFile(source, destination)
if (expectedSize != null && (await stat(destination)).size !== expectedSize) {
throw new Error('专属素材文件复制不完整')
}
return storedPath
}