From c43e1fea5094359a220f3f2aa3bacda2cec57685 Mon Sep 17 00:00:00 2001 From: CaptainB Date: Fri, 11 Jul 2025 11:19:18 +0800 Subject: [PATCH] refactor: improve filename extraction logic in content disposition handling --- ui/src/request/index.ts | 38 +++++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/ui/src/request/index.ts b/ui/src/request/index.ts index 58d626a2b..f969956ac 100644 --- a/ui/src/request/index.ts +++ b/ui/src/request/index.ts @@ -249,17 +249,33 @@ export const exportExcel: ( ) } -function decodeFilenameBrowser(contentDisposition: string) { - // 提取并解码 Base64 部分 - const base64Part = contentDisposition.match(/=\?utf-8\?b\?(.*?)\?=/i)?.[1] - if (!base64Part) return null +function extractFilename(contentDisposition: string) { + if (!contentDisposition) return null; - // 使用 atob 解码 Base64 - const decoded = decodeURIComponent(escape(atob(base64Part))) + // 处理 URL 编码的文件名 + const urlEncodedMatch = contentDisposition.match(/filename=([^;]*)/i) || + contentDisposition.match(/filename\*=UTF-8''([^;]*)/i); + if (urlEncodedMatch && urlEncodedMatch[1]) { + try { + return decodeURIComponent(urlEncodedMatch[1].replace(/"/g, '')); + } catch (e) { + console.error("解码URL编码文件名失败:", e); + } + } - // 提取文件名 - const filenameMatch = decoded.match(/filename="(.*?)"/i) - return filenameMatch ? filenameMatch[1] : null + // 处理 Base64 编码的文件名 + const base64Part = contentDisposition.match(/=\?utf-8\?b\?(.*?)\?=/i)?.[1]; + if (base64Part) { + try { + const decoded = decodeURIComponent(escape(atob(base64Part))); + const filenameMatch = decoded.match(/filename="(.*?)"/i); + return filenameMatch ? filenameMatch[1] : null; + } catch (e) { + console.error("解码Base64文件名失败:", e); + } + } + + return null; } export const exportFile: ( @@ -296,9 +312,9 @@ export const exportFile: ( // const contentType = headers['content-type']; const contentDisposition = headers['content-disposition'] // console.log('Content-Type:', contentType); - // console.log('Content-Disposition:', decodeFilenameBrowser(contentDisposition)); + // console.log('Content-Disposition:', contentDisposition); // 如果没有提供文件名,则使用默认名称 - fileName = decodeFilenameBrowser(contentDisposition) || fileName + fileName = extractFilename(contentDisposition) || fileName return data // 必须返回数据 }, ],