简体   繁体   English

HTML 无法正确读取图像标签 src 中的 unicode

[英]HTML can't properly read unicode in image tag src

I am using electron with html, css and js.我将电子与 html、css 和 js 一起使用。 For my desktop app, I want to import an image from my local storage using an img tag.对于我的桌面应用程序,我想使用 img 标签从本地存储导入图像。 However, my file name contains an unicode (eg #).但是,我的文件名包含一个 unicode(例如 #)。 When, HTML try to fetch the image it gets rid of the second half part of the file name starting from the unicode.See the example below please.当 HTML 尝试获取图像时,它会去掉从 unicode 开始的文件名的后半部分。请参见下面的示例。

<img src= "path/to/my/example#file.png">

This becomes, src= "path/to/my/example"这变成了 src="path/to/my/example"

by deleting the part after the Unicode.通过删除 Unicode 之后的部分。 Returning me ERR_FILE_NOT_FOUND in console.在控制台中返回我 ERR_FILE_NOT_FOUND。

using %23 may be an option however, The filename is unfortunately unpredictable and it changes based on the file (I import several pictures).使用 %23 可能是一个选项,但是不幸的是,文件名是不可预测的,它会根据文件而变化(我导入了几张图片)。 So, obtaining the filename and creating the HTML tag is automized using javascript.因此,获取文件名和创建 HTML 标记是使用 javascript 自动完成的。 Is there a way for the javascirpt to automatically catch unicode in a string (path to file) and enforce it so that html can read it? javascirpt 有没有办法自动捕获字符串(文件路径)中的 unicode 并强制执行它以便 html 可以读取它?

You need to 'url encode' also known as 'percent encode' all special characters.您需要对所有特殊字符进行“url 编码”也称为“百分比编码”。 In your example, replace the # with %23 .在您的示例中,将#替换为%23

You also incorrectly used : instead of = in the attribute:您还错误地使用了:而不是属性中的=

<img src="path/to/my/example#file.png">

# is not a "unicode" as you call it. #不是你所说的“unicode”。 It is just a plain ASCII character.它只是一个普通的 ASCII 字符。 But, within a url, it just happens to be a reserved character, used to denote an anchor within a resource, and so is not part of the resource's path, which is why you see it getting stripped off.但是,在 url 中,它恰好是一个保留字符,用于表示资源中的锚点,因此不是资源路径的一部分,这就是为什么你会看到它被剥离的原因。

So, you must url-encode (ie, percent-encode) the # character as %23 if it is meant to be used inside the path itself, eg:因此,如果要在路径本身内部使用#字符,则必须将其 url 编码(即百分比编码)为%23 ,例如:

<img src="path/to/my/example%23file.png">

Since you said that you need to generate this HTML via JavaScript, you will need to have your script parse the file path and encode any reserved characters as needed.由于您说您需要通过 JavaScript 生成此 HTML,因此您需要让您的脚本解析文件路径并根据需要对任何保留字符进行编码。 In fact, JavaScript has built-in functions for this exact purpose: encodeURI() and encodeURIComponent() .事实上,JavaScript 已经为此目的内置了函数: encodeURI()encodeURIComponent()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM