From 8f141188a3c53f73af52149c891b00da1b8935a4 Mon Sep 17 00:00:00 2001 From: jingrow Date: Fri, 2 Jan 2026 20:23:02 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E4=BC=98=E5=8C=96=E5=8E=BB?= =?UTF-8?q?=E8=83=8C=E6=99=AF=E5=B7=A5=E5=85=B7=E4=BB=A3=E7=A0=81=EF=BC=8C?= =?UTF-8?q?=E6=B6=88=E9=99=A4=E6=96=87=E4=BB=B6=E5=86=85=E9=83=A8=E9=87=8D?= =?UTF-8?q?=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在文件内部提取 handleSuccess 辅助函数,消除成功处理逻辑重复 - 简化流式响应处理代码,提高可读性和可维护性 - 保持工具文件独立性,符合设计原则 --- src/views/HomePage.vue | 70 +++++++------------ .../remove_background/remove_background.vue | 69 +++++++----------- 2 files changed, 52 insertions(+), 87 deletions(-) diff --git a/src/views/HomePage.vue b/src/views/HomePage.vue index 95e4c6c..3994990 100644 --- a/src/views/HomePage.vue +++ b/src/views/HomePage.vue @@ -517,11 +517,30 @@ const handleRemoveBackground = async () => { processing.value = true resultImage.value = '' + // 处理成功结果的辅助函数(文件内部使用) + const handleSuccess = async (imageUrl: string): Promise => { + resultImage.value = imageUrl + await cacheResultImage(imageUrl) + + if (currentHistoryIndex.value === -1 && uploadedImage.value && uploadedImageUrl.value) { + const historyItem: HistoryItem = { + id: `history-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + originalImageUrl: uploadedImageUrl.value, + originalImageFile: uploadedImage.value, + resultImage: imageUrl, + timestamp: Date.now() + } + historyList.value.unshift(historyItem) + currentHistoryIndex.value = 0 + } else if (currentHistoryIndex.value >= 0) { + historyList.value[currentHistoryIndex.value].resultImage = imageUrl + } + } + try { const formData = new FormData() formData.append('file', uploadedImage.value) - // 使用 fetch 处理流式响应(NDJSON 格式) const controller = new AbortController() const timeoutId = setTimeout(() => controller.abort(), 180000) @@ -537,7 +556,6 @@ const handleRemoveBackground = async () => { throw new Error(`HTTP error! status: ${response.status}`) } - // 读取流式响应(NDJSON 格式,每行一个 JSON 对象) const reader = response.body?.getReader() const decoder = new TextDecoder() let buffer = '' @@ -552,38 +570,17 @@ const handleRemoveBackground = async () => { buffer += decoder.decode(value, { stream: true }) const lines = buffer.split('\n') - buffer = lines.pop() || '' // 保留最后一个不完整的行 + buffer = lines.pop() || '' - // 处理完整的行 for (const line of lines) { if (line.trim()) { try { const result = JSON.parse(line.trim()) - - // 后端返回格式:{"status": "success", "image_url": "..."} if (result.status === 'success' && result.image_url) { - resultImage.value = result.image_url - - // 缓存图片 blob URL 用于下载 - await cacheResultImage(result.image_url) - - // 添加到历史记录 - if (currentHistoryIndex.value === -1 && uploadedImage.value && uploadedImageUrl.value) { - const historyItem: HistoryItem = { - id: `history-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, - originalImageUrl: uploadedImageUrl.value, - originalImageFile: uploadedImage.value, - resultImage: result.image_url, - timestamp: Date.now() - } - historyList.value.unshift(historyItem) - currentHistoryIndex.value = 0 - } else if (currentHistoryIndex.value >= 0) { - historyList.value[currentHistoryIndex.value].resultImage = result.image_url - } - return // 成功处理,退出 - } else { - message.error(result.error || t('Failed to remove background')) + await handleSuccess(result.image_url) + return + } else if (result.error) { + message.error(result.error) } } catch (parseError) { console.error('Failed to parse JSON:', parseError, 'Line:', line) @@ -597,22 +594,7 @@ const handleRemoveBackground = async () => { try { const result = JSON.parse(buffer.trim()) if (result.status === 'success' && result.image_url) { - resultImage.value = result.image_url - await cacheResultImage(result.image_url) - - if (currentHistoryIndex.value === -1 && uploadedImage.value && uploadedImageUrl.value) { - const historyItem: HistoryItem = { - id: `history-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, - originalImageUrl: uploadedImageUrl.value, - originalImageFile: uploadedImage.value, - resultImage: result.image_url, - timestamp: Date.now() - } - historyList.value.unshift(historyItem) - currentHistoryIndex.value = 0 - } else if (currentHistoryIndex.value >= 0) { - historyList.value[currentHistoryIndex.value].resultImage = result.image_url - } + await handleSuccess(result.image_url) return } else { message.error(result.error || t('Failed to remove background')) diff --git a/src/views/tools/remove_background/remove_background.vue b/src/views/tools/remove_background/remove_background.vue index 004a155..08428cc 100644 --- a/src/views/tools/remove_background/remove_background.vue +++ b/src/views/tools/remove_background/remove_background.vue @@ -608,11 +608,30 @@ const handleRemoveBackground = async () => { processing.value = true resultImage.value = '' + // 处理成功结果的辅助函数(文件内部使用) + const handleSuccess = async (imageUrl: string): Promise => { + resultImage.value = imageUrl + await cacheResultImage(imageUrl) + + if (currentHistoryIndex.value === -1 && uploadedImage.value && uploadedImageUrl.value) { + const historyItem: HistoryItem = { + id: `history-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + originalImageUrl: uploadedImageUrl.value, + originalImageFile: uploadedImage.value, + resultImage: imageUrl, + timestamp: Date.now() + } + historyList.value.unshift(historyItem) + currentHistoryIndex.value = 0 + } else if (currentHistoryIndex.value >= 0) { + historyList.value[currentHistoryIndex.value].resultImage = imageUrl + } + } + try { const formData = new FormData() formData.append('file', uploadedImage.value) - // 使用 fetch 处理流式响应(NDJSON 格式) const controller = new AbortController() const timeoutId = setTimeout(() => controller.abort(), 180000) @@ -628,7 +647,6 @@ const handleRemoveBackground = async () => { throw new Error(`HTTP error! status: ${response.status}`) } - // 读取流式响应(NDJSON 格式,每行一个 JSON 对象) const reader = response.body?.getReader() const decoder = new TextDecoder() let buffer = '' @@ -643,37 +661,17 @@ const handleRemoveBackground = async () => { buffer += decoder.decode(value, { stream: true }) const lines = buffer.split('\n') - buffer = lines.pop() || '' // 保留最后一个不完整的行 + buffer = lines.pop() || '' - // 处理完整的行 for (const line of lines) { if (line.trim()) { try { const result = JSON.parse(line.trim()) - - // 后端返回格式:{"status": "success", "image_url": "..."} if (result.status === 'success' && result.image_url) { - resultImage.value = result.image_url - - // 缓存图片 blob URL 用于下载 - await cacheResultImage(result.image_url) - - if (currentHistoryIndex.value === -1 && uploadedImage.value && uploadedImageUrl.value) { - const historyItem: HistoryItem = { - id: `history-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, - originalImageUrl: uploadedImageUrl.value, - originalImageFile: uploadedImage.value, - resultImage: result.image_url, - timestamp: Date.now() - } - historyList.value.unshift(historyItem) - currentHistoryIndex.value = 0 - } else if (currentHistoryIndex.value >= 0) { - historyList.value[currentHistoryIndex.value].resultImage = result.image_url - } - return // 成功处理,退出 - } else { - message.error(result.error || t('Failed to remove background')) + await handleSuccess(result.image_url) + return + } else if (result.error) { + message.error(result.error) } } catch (parseError) { console.error('Failed to parse JSON:', parseError, 'Line:', line) @@ -687,22 +685,7 @@ const handleRemoveBackground = async () => { try { const result = JSON.parse(buffer.trim()) if (result.status === 'success' && result.image_url) { - resultImage.value = result.image_url - await cacheResultImage(result.image_url) - - if (currentHistoryIndex.value === -1 && uploadedImage.value && uploadedImageUrl.value) { - const historyItem: HistoryItem = { - id: `history-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, - originalImageUrl: uploadedImageUrl.value, - originalImageFile: uploadedImage.value, - resultImage: result.image_url, - timestamp: Date.now() - } - historyList.value.unshift(historyItem) - currentHistoryIndex.value = 0 - } else if (currentHistoryIndex.value >= 0) { - historyList.value[currentHistoryIndex.value].resultImage = result.image_url - } + await handleSuccess(result.image_url) return } else { message.error(result.error || t('Failed to remove background'))