我有一个文本文件(这里是 big_buck_bunny_trailer_480p.srt
),它是一个 html 页面的“兄弟”(所以当我在本地运行 html 页面时,它是一个本地文件 - 当我在服务器上运行它时,它是一个远程文件) - 目录结构是:
.
├── big_buck_bunny_trailer_480p.srt
└── ttt.html
我正在尝试使用 XMLHttpRequest
读取文本文件;成功了,我可以得到文本文件的字符串内容。但是当我尝试从中创建一个 Blob 时,在 Firefox 60 控制台中我得到“不可用”。
这是我的测试文件,ttt.html
:
<script type="text/javascript">
function reqListener () {
console.log(this.responseText);
var myblob = new Blob([this.responseText], {
type: 'text/plain'
});
console.log(myblob);
}
var oReq = new XMLHttpRequest(); // "To read files that are siblings of the HTML document, use XMLHttpRequest"
oReq.addEventListener("load", reqListener);
oReq.open("GET", "big_buck_bunny_trailer_480p.srt");
oReq.send();
</script>
当我在 Firefox 60 中运行它时,控制台打印出:
1 ttt.html:4:3
00:00:00,005 --> 00:00:03,800
The peach open movie project presents
(...)
<unavailable> ttt.html:8:3
The character encoding of the HTML document was not declared. ...
XML Parsing Error: syntax error
Location: file:///tmp/test/big_buck_bunny_trailer_480p.srt
Line Number 1, Column 1: big_buck_bunny_trailer_480p.srt:1:1
所以,我得到了正确的字符串 - 但为什么 Blob <unavailable>
?我怎样才能从这个字符串中得到一个 Blob?
奖励问题:我明白为什么会出现“未声明 HTML 文档的字符编码”警告,- 毕竟,我什至没有 <html>
在我的 html 文件中。但是为什么XML Parsing Error: syntax error
出现?我只要求读取这个文件,而不是解析它?如果解析是自动的,我能否以某种方式阻止它 - 我只需要字符串内容?
编辑:将示例简化为:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
var myblob = new Blob([window.btoa("Hello world")], {
type: 'text/plain'
});
console.log(myblob);
</script>
</head>
</html>
...并使用 python -m SimpleHTTPServer
访问它, 所以通过 http://127.0.0.1:8000/ttt.html
;我在控制台中得到的唯一打印输出是:
<unavailable> ttt.html:22:3
那么,如何从字符串中获取实际的 blob?
最佳答案
您的html 标签
可能中断
xml 解析
。这就是它抛出 Syntax Error.
的原因。这种错误在 JSON
或 XML 解析
中很常见。在创建 Blob 之前,对 Response Data
进行编码。
试试这个,
new Blob([window.btoa(this.responseText)], {
type: 'text/plain'
});
此外,当您从 Blob
检索数据时。您需要使用 window.atob()
进行解码。
关于javascript - 同级文本文件字符串到 JavaScript 中的 blob - 不可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54039883/