diff --git a/src/main/ipc.js b/src/main/ipc.js index 2a96145..ebe1e32 100644 --- a/src/main/ipc.js +++ b/src/main/ipc.js @@ -244,39 +244,49 @@ export function setupIPC() { }); // 下载文件并打开下载目录 - ipcMain.handle('downloadFile', async (event, { fileUrl }) => { + ipcMain.handle('downloadFile', async (event, fileUrl) => { logger.info("=============================开始下载文件:",fileUrl) - try { - // 从URL中提取文件名 - const url = new URL(fileUrl); - const pathname = url.pathname; - let fileName = path.basename(pathname); - // 如果URL中没有文件名或文件名为空,使用默认名称 - if (!fileName || fileName === '' || fileName === '/') { + try { + // 解码URL + fileUrl = decodeURI(fileUrl); + + // 简单提取文件名:从URL路径的最后一部分获取 + let fileName = ''; + try { + const url = new URL(fileUrl); + const pathSegments = url.pathname.split('/').filter(segment => segment); + fileName = pathSegments[pathSegments.length - 1] || ''; + } catch (error) { + // 如果URL解析失败,尝试直接从字符串中提取 + const urlParts = fileUrl.split('/'); + fileName = urlParts[urlParts.length - 1] || ''; + } + + // 解码文件名,解决中文乱码问题 + try { + fileName = decodeURIComponent(fileName); + } catch (error) { + // 如果解码失败,保持原文件名 + logger.warn(`文件名解码失败: ${fileName}`); + } + + // 如果提取的文件名为空,使用时间戳生成默认名称 + if (!fileName || fileName === '') { fileName = `downloaded_file_${Date.now()}`; } - // 如果文件名没有扩展名,尝试从Content-Disposition头获取 - const response = await axios({ - method: "head", - url: fileUrl - }); - - const contentDisposition = response.headers["content-disposition"]; - if (contentDisposition) { - const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/); - if (filenameMatch && filenameMatch[1]) { - const extractedFileName = filenameMatch[1].replace(/['"]/g, ''); - if (extractedFileName && path.extname(extractedFileName)) { - fileName = extractedFileName; - } - } + // 获取用户下载目录 + const downloadDir = path.join(os.homedir(), 'Downloads'); + + // 确保下载目录存在 + if (!fs.existsSync(downloadDir)) { + fs.mkdirSync(downloadDir, { recursive: true }); } - - const outputLocationPath = path.join(os.tmpdir(), fileName); + + const outputLocationPath = path.join(downloadDir, fileName); const writer = fs.createWriteStream(outputLocationPath); let receivedBytes = 0;