* 附件处理器 * 管理文件附件的本地存储
| 7 | * 管理文件附件的本地存储 |
| 8 | */ |
| 9 | class AttachmentHandler { |
| 10 | private attachmentsDir: string |
| 11 | |
| 12 | constructor() { |
| 13 | // 附件存储目录:应用数据目录/attachments |
| 14 | this.attachmentsDir = path.join(app.getPath('userData'), 'attachments') |
| 15 | } |
| 16 | |
| 17 | /** |
| 18 | * 保存附件到本地 |
| 19 | * @param fileId 文件ID |
| 20 | * @param fileName 文件名 |
| 21 | * @param base64Content base64编码的文件内容 |
| 22 | * @param pageId 页面ID(可选) |
| 23 | * @param messageId 消息ID(可选) |
| 24 | * @returns 相对路径 |
| 25 | */ |
| 26 | async saveAttachment( |
| 27 | fileId: string, |
| 28 | fileName: string, |
| 29 | base64Content: string, |
| 30 | pageId?: string, |
| 31 | messageId?: string |
| 32 | ): Promise<{ success: boolean; localPath?: string; error?: string }> { |
| 33 | try { |
| 34 | // 确定存储路径 |
| 35 | let targetDir: string |
| 36 | if (pageId && messageId) { |
| 37 | targetDir = path.join(this.attachmentsDir, pageId, messageId) |
| 38 | } else { |
| 39 | targetDir = path.join(this.attachmentsDir, 'temp') |
| 40 | } |
| 41 | |
| 42 | // 创建目录 |
| 43 | await mkdir(targetDir, { recursive: true }) |
| 44 | |
| 45 | // 提取文件扩展名 |
| 46 | const ext = path.extname(fileName) |
| 47 | const filePath = path.join(targetDir, `${fileId}${ext}`) |
| 48 | |
| 49 | // 写入文件 |
| 50 | const buffer = Buffer.from(base64Content, 'base64') |
| 51 | await writeFile(filePath, buffer) |
| 52 | |
| 53 | // 返回相对路径 |
| 54 | const relativePath = path.relative(this.attachmentsDir, filePath) |
| 55 | return { success: true, localPath: relativePath } |
| 56 | } catch (error) { |
| 57 | console.error('保存附件失败:', error) |
| 58 | return { |
| 59 | success: false, |
| 60 | error: error instanceof Error ? error.message : '保存附件失败' |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * 读取附件内容 |
nothing calls this directly
no outgoing calls
no test coverage detected