我正在尝试将序列化的json数据写入文件。我正在使用application/octet-stream
,但是在运行代码时,它会删除所有空格(即使在字符串内)。如何避免这种情况?
const link = document.createElement("a")
link.download = "file.json"
link.href = "data:application/octet-stream," + content
link.click()
答案 0 :(得分:2)
要获得预期的结果,请使用encodeURI保留空白
var content = `Morgan Freeman`
const link = document.createElement("a")
link.download = "file.json"
link.href = "data:application/octet-stream," + encodeURI(content)
link.click()
codepen-https://codepen.io/nagasai/pen/NVwgKg?editors=1010
encodeURI将转义序列添加到空格,并在那里保留空格
用%20代替空间,即Morgan%20Freeman
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI
答案 1 :(得分:0)
您可以将content
编码为base64,例如
data:application/octet-stream;base64,eyJhIiA6ICJoZWxsbyB3b3JsZCJ9
^-----^ Notice this
会解码为{"a" : "hello world"}
个保留空间。