简体   繁体   English

React:如何通过包含特殊字符的路径加载图像?

[英]React: How to load an image by path that contains special characters?

I have tried to load an image by path that contains special characters like &@^.我试图通过包含 &@^ 等特殊字符的路径加载图像。

When I loaded the image as below, it didn't work.当我如下加载图像时,它不起作用。

<img src="file:///test/@#$%/0.png"/>

So, I've tried to use encodeURI(path), encodeURIComponent(path), but it didn't work too.因此,我尝试使用 encodeURI(path)、encodeURIComponent(path),但也没有用。

How can I do this?我怎样才能做到这一点?

You have to encode each level in your path (skip the / characters) like this:您必须像这样对路径中的每个级别进行编码(跳过/字符):

const path = 'file:///test/@#$%/0.png'
const encodedPath = 'file://' + path.replace('file://', '').split('/').map((p) => encodeURIComponent(p)).join('/')
console.log(encodedPath)
// Output: file:///test/%40%23%24%25/0.png

Use the above output for your img tag, it will be loaded.使用上面的 output 作为您的img标签,它将被加载。

You cannot render them as string.您不能将它们呈现为字符串。 If you want to use them, you must write on Numeric code or JS escape.如果你想使用它们,你必须写上数字代码或 JS 转义。

You can find their codes from here你可以从这里找到他们的代码

As your wanted,如你所愿,

@ : &#64;
# : &#35;
$ : &#36;

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

相关问题 react中如何通过props加载图片路径 - How to load a image path through props in react 如何在 react.js 中加载具有绝对路径的图像 - How to load a image with absolute path in react.js 如何在 img src 中指定图像本地路径以在 react/JavaScript 中加载 - How to specify image local path in img src to load in react/JavaScript 如何格式化包含特殊字符的javascript数组数据 - how to format javascript array data that contains special characters 如何将字符串传递给包含特殊字符的javascript函数 - How to pass string to javascript funciton which contains special characters 如何创建名称中包含特殊字符的自定义元素? - How to create a custom element that contains special characters in its name? 如何对包含特殊字符和空格的字符串数组进行排序 - how to sort an array of string which contains special characters and white spaces 如何在JavaScript中使用包含特殊字符的正则表达式 - How to use a Regular Expression in JavaScript which contains special characters 如何使用 javascript 检查输入是否包含特殊字符 - How to use javascript to check if input contains special characters 如果包含特殊字符,如何正确编码JavaScript URL? - How to encode a JavaScript URL correctly if it contains special characters?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM