🐞 fix: 添加文件名清理功能以处理非法字符

- 新增 sanitizeFilename 函数,清理文件名中的非法字符
- 在下载音乐功能中应用清理后的文件名,确保文件名有效性

fixed: #78
This commit is contained in:
alger
2025-03-14 21:19:23 +08:00
parent 6a8813531f
commit df9a1370c3

View File

@@ -257,6 +257,17 @@ async function processDownloadQueue(event: Electron.IpcMainEvent) {
}
}
/**
* 清理文件名中的非法字符
*/
function sanitizeFilename(filename: string): string {
// 替换 Windows 和 Unix 系统中的非法字符
return filename
.replace(/[<>:"/\\|?*]/g, '_') // 替换特殊字符为下划线
.replace(/\s+/g, ' ') // 将多个空格替换为单个空格
.trim(); // 移除首尾空格
}
/**
* 下载音乐功能
*/
@@ -276,9 +287,12 @@ async function downloadMusic(
const store = new Store();
const downloadPath = (store.get('set.downloadPath') as string) || app.getPath('downloads');
// 清理文件名中的非法字符
const sanitizedFilename = sanitizeFilename(filename);
// 从URL中获取文件扩展名如果没有则使用传入的type或默认mp3
const urlExt = type ? `.${type}` : '.mp3';
const filePath = path.join(downloadPath, `${filename}${urlExt}`);
const filePath = path.join(downloadPath, `${sanitizedFilename}${urlExt}`);
// 检查文件是否已存在,如果存在则添加序号
finalFilePath = filePath;