API/src/service/upload.service.ts

44 lines
1.2 KiB
TypeScript

import { Provide } from '@midwayjs/core';
import * as fs from 'fs';
import * as path from 'path';
import { v4 as uuidv4 } from 'uuid';
@Provide()
export class UploadService {
async uploadBase64<T>(
base64: string,
filename: string,
callback: (filePath: string) => Promise<T>
): Promise<T> {
// 从base64字符串中提取数据
const matches = base64.match(/^data:(.+);base64,(.+)$/);
if (!matches || matches.length !== 3) {
throw new Error('Invalid base64 string');
}
// 解码base64数据
const buffer = Buffer.from(matches[2], 'base64');
// 创建一个唯一的文件名
const uniqueFilename = `${uuidv4()}-${filename}`;
const filePath = path.join('/tmp', uniqueFilename);
try {
// 将文件写入临时目录
await fs.promises.writeFile(filePath, buffer);
// 执行回调并传递文件路径
return await callback(filePath);
} finally {
// 确保临时文件被删除
try {
await fs.promises.unlink(filePath);
} catch (error) {
// 如果文件不存在或无法删除,则记录错误
console.error(`Failed to delete temporary file: ${filePath}`, error);
}
}
}
}