From 60bc89ffea94ba27dbe17ea9780e5794e3bc1aa9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=96=BB=E5=8B=87=E7=A5=A5?= <237899745@qq.com> Date: Tue, 11 Nov 2025 15:06:20 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D:=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E4=B8=8B=E8=BD=BD=E6=97=B6storage=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E8=B5=84=E6=BA=90=E6=B3=84=E6=BC=8F=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 问题: - /api/files/download 路由在文件流下载时没有关闭storage连接 - 当下载大文件或多个并发下载时,会导致SFTP连接积累 - 可能导致连接池耗尽和内存泄漏 修复内容: 1. 添加stream.on('error')事件处理:流错误时关闭storage连接 2. 添加stream.on('close')事件处理:流传输完成时关闭storage连接 3. 增强catch块:在stream创建之前发生错误时关闭storage连接 影响范围: - /api/files/download(用户文件下载) - /api/share/:code/download-file(分享文件下载,已有处理逻辑) 测试建议: - 测试正常文件下载 - 测试下载过程中断(用户取消下载) - 测试下载不存在的文件(错误处理) - 测试大文件下载和并发下载 --- backend/server.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/backend/server.js b/backend/server.js index b720b78..c5865cf 100644 --- a/backend/server.js +++ b/backend/server.js @@ -923,12 +923,32 @@ app.get('/api/files/download', authMiddleware, async (req, res) => { message: '文件下载失败: ' + error.message }); } + // 发生错误时关闭存储连接 + if (storage) { + storage.end().catch(err => console.error('关闭存储连接失败:', err)); + } + }); + + // 在传输完成后关闭存储连接 + stream.on('close', () => { + console.log('[下载] 文件传输完成,关闭存储连接'); + if (storage) { + storage.end().catch(err => console.error('关闭存储连接失败:', err)); + } }); stream.pipe(res); + + + } catch (error) { console.error('下载文件失败:', error); + + // 如果stream还未创建或发生错误,关闭storage连接 + if (storage) { + storage.end().catch(err => console.error('关闭存储连接失败:', err)); + } if (!res.headersSent) { res.status(500).json({ success: false,