Electron中通过showOpenDialog选择含特殊字符的文件路径出现乱码的问题咨询
Electron中通过showOpenDialog选择含特殊字符的文件路径出现乱码的问题咨询
我正在开发一个Electron应用,用户可以通过dialog.showOpenDialog选择文件。选中的文件路径会被记录和处理,但包含特殊字符(比如茅、鈥�这类)的文件路径在日志和处理过程中显示异常。举个例子:
实际选择的文件路径:
E:\m\upload\Casselberry-DuPre茅 鈥�City Down\B2 - War.flac
我的Electron应用保存的路径:
E:\m\upload\Casselberry-DuPre鈹溾寪 螕脟么 City Down\B2 - War.flac
我试过多种路径清理的方法,但问题依然存在。想请教大家:有没有合适的npm解决方案(最好不用额外导入包)能正确获取路径?另外,为什么Electron会把路径弄成这样呢?
我的代码如下:
ipcMain.on('open-file-dialog', async (event) => { try { const result = await dialog.showOpenDialog({ properties: ['openFile', 'multiSelections'] }); if (!result.canceled && result.filePaths.length > 0) { const fileInfoArray = await Promise.all( result.filePaths.map(async (filePath) => { // Normalize and decode file path to handle special characters const normalizedPath = path.resolve(filePath); console.log('normalizedPath = ', normalizedPath); // Decode using iconv-lite to handle special characters const decodedPath = iconv.decode(Buffer.from(normalizedPath, 'binary'), 'utf-8'); console.log('decodedPath = ', decodedPath); const ext = path.extname(decodedPath).toLowerCase().substring(1); // Extract extension without the dot let fileType = 'other'; // Default file type let dimensions = null; if (audioExtensions.includes(ext)) { fileType = 'audio'; } else if (imageExtensions.includes(ext)) { fileType = 'image'; try { const metadata = await sharp(decodedPath).metadata(); dimensions = `${metadata.width}x${metadata.height}`; } catch (error) { console.error('Error reading image dimensions:', error); } } console.log('setting filePath = ', decodedPath); // Log decoded path return { filename: path.basename(decodedPath), // Use `filename` filepath: decodedPath, filetype: fileType, dimensions, // Include dimensions if available }; }) ); event.sender.send('selected-file-paths', fileInfoArray); } } catch (error) { console.error('Error opening file dialog:', error); } });
日志输出:
normalizedPath = E:\martinradio\upload\Casselberry-DuPre鈹溾寪 螕脟么 City Down\B2 - War.flac decodedPath = E:\martinradio\upload\Casselberry-DuPre鈭┾攼鈺�鈥�City Down\B2 - War.flac setting filePath = E:\martinradio\upload\Casselberry-DuPre鈭┾攼鈺�鈥�City Down\B2 - War.flac
备注:内容来源于stack exchange,提问作者Martin
相关产品推荐
相关产品推荐

