JavaScript Encodeuri与CSV无法正常工作
我正在尝试通过Code Bellow生成简短的CSV:
source
const csv_content = `"Hello"þ"World"þ"#"þ"123"`;
const href = 'data:attachment/csv;charset=utf-8,' + encodeURI(csv_content);
console.log(href);
我在浏览器中复制/经过 href value 并下载它。
href的值
data:attachment/csv;charset=utf-8,%22Hello%22%C3%BE%22World%22%C3%BE%22#%22%C3%BE%22123%22
我在Excel中打开它,但是我无法在# char和#本身之后显示任何字符。 如果有人可以解释我为什么 encodeuri 和#回到我这个问题,那真是太好了!
解决方案
EvolutionXbox
注释解决此问题,您需要使用 encodeuricomponent 而不是encodeuri
// encodes characters such as ?,=,/,&,:
console.log(`?x=${encodeURIComponent('test?')}`);
// expected output: "?x=test%3F"
I'm trying generate short CSV by the code bellow :
Source
const csv_content = `"Hello"þ"World"þ"#"þ"123"`;
const href = 'data:attachment/csv;charset=utf-8,' + encodeURI(csv_content);
console.log(href);
I copy/past the href value in my browser and download it.
Value of href
data:attachment/csv;charset=utf-8,%22Hello%22%C3%BE%22World%22%C3%BE%22#%22%C3%BE%22123%22
I open it in Excel but I can't show any chars after # char and the # itself.
If someone can explain me why encodeURI and # return me this issue, that would be wonderfull !
SOLUTION
evolutionxbox
comment resolve this issue, you need use encodeURIComponent instead encodeURI
// encodes characters such as ?,=,/,&,:
console.log(`?x=${encodeURIComponent('test?')}`);
// expected output: "?x=test%3F"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的问题实际上涉及一个重要的话题,这就是在URL中与应该通过的内容在体内通过的内容。
当您像CSV文件一样到达复杂的对象时,最好使用身体来保存此信息,因为它对字符的挑剔要少得多。
另一个原因是URL是开放和未受保护的信息。如果您制作了包含敏感数据的CSV文件,那么世界上任何人都可以看到它。人体中的数据(假设您正在使用HTTPS)是加密的,并且并非向所有观看者打开。
记住
get
,put
,patch
,delete
和发布的正确用途也很重要。
。在发送文件时,很难按下有充分的理由将get
用作请求者(如果请求者是发送CSV文件的一个),这是以上唯一的一个违反公约以在请求正文中发送数据。但是,在获取
响应主体中将数据完全可以。Your issue actually touches on an important topic, and that is what should be passed in a URL vs what should be passed in the body.
When you get to complex objects, like a csv file, it would be best to use the body to hold this information, as it is much less picky about characters.
Another reason is that the URL is open and unprotected information. If you ever made a csv file that contained sensitive data, anybody in the world can see it. Data in the body (assuming you are using https) is encrypted and not open to all viewers.
It is also important to remember the correct uses for
GET
,PUT
,PATCH
,DELETE
andPOST
. When working with sending a file I would be hard pressed to find a good reason to useGET
as the requestor (if the requestor is the one sending the csv file), the only one of the above where it breaks convention to send data in the body of the request. It is perfectly okay to have data in aGET
response body though.解决方案
EvolutionXbox
注释解决此问题,您需要使用 encodeuricomponent 而不是encodeuri
SOLUTION
evolutionxbox
comment resolve this issue, you need use encodeURIComponent insteadencodeURI