Flutter/Dart中如何将含UTF8十六进制编码的字符串转为Latin1字符?
解决URL百分号编码字符串转实际字符的问题
你遇到的是URL百分号编码的解码问题,不是单纯的字符集编码转换,之前用latin1/utf8的encode/decode方法不对路,因为%C3%A9是把UTF-8字节(对应字符"é"的UTF-8编码是0xC3 0xA9)转成了URL安全的百分号格式,直接用专门的URL解码函数就能解决:
浏览器端解决方案
用全局的decodeURIComponent()函数直接解码:
const encodedFileName = "A_Escadaria--Fernand_L%C3%A9ger.jpg"; const decodedFileName = decodeURIComponent(encodedFileName); console.log(decodedFileName); // 输出: A_Escadaria--Fernand_Léger.jpg
Node.js端解决方案
Node.js同样支持全局的decodeURIComponent(),用法和浏览器一致:
const encodedFileName = "A_Escadaria--Fernand_L%C3%A9ger.jpg"; const decodedFileName = decodeURIComponent(encodedFileName); console.log(decodedFileName); // 输出: A_Escadaria--Fernand_Léger.jpg
为什么之前的方法无效?
你尝试的latin1.encode/decode、utf8.encode/decode是处理字节数组与字符串之间的转换,但这里的%C3%A9是URL编码的字符串表示,需要先把百分号格式转成对应的字节,再解码成字符——decodeURIComponent()已经帮你完成了这两步:识别百分号编码→转成UTF-8字节→解码为对应字符,完全匹配你的需求。
如果遇到的是基于Latin1的百分号编码(比如%E9表示"é"),可以先解码成字节再用Latin1转字符串:
// 示例:处理Latin1编码的%E9 const encodedStr = "Fernand_L%E9ger.jpg"; const bytes = new Uint8Array(decodeURIComponent(encodedStr).split('').map(c => c.charCodeAt(0))); const decodedStr = new TextDecoder('latin1').decode(bytes); console.log(decodedStr); // 输出: Fernand_Léger.jpg
不过你的场景里是UTF-8的百分号编码,用第一种方法就足够。
内容的提问来源于stack exchange,提问作者Carlos Humberto Borges
相关产品推荐
相关产品推荐

