当涉及到Node.js中的文件名时,我遇到了一个问题,其中某些传入文件带有井号#
,这在使用文件系统然后使用从文件名派生的URL来在<img>
标签中重新访问它时会导致问题。
var fileDir = "/foo/bar#s.png/";
var dirContents = fs.readdirSync(fileDir);
document.getElementById("id1").src = encodeURIComponent(path.join('cache', fileDir, dirContents[0]))
// %2Fcache%2Ffoo%2Fbar%23s.png%2Fbar%23s%2001.png :: Broken img
document.getElementById("id2").src = path.join('cache', fileDir, dirContents[1])
// /cache/foo/bar#s.png/bar#s 02.png :: Also broken img
我可以控制目录名称,但是最终文件.png
s由加载文件的用户决定。我该如何处理这些字符?
您将逃脱这些字符:
document.getElementById("id1").src = path.join('cache',
...fileDir.split("/").map(encodeURIComponent),
encodeURIComponent(dirContents[0]));
但是,您将需要确保服务器在收到图像请求时再次正确地对其解码,并非所有实现都同意如何处理文件路径中的百分比编码。一种更简单,可能更好的方法是首先防止这些字符出现在文件名中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句