我正在尝试下载大型 json 数据。
但它会导致Uncaught RangeError: Invalid string length
。
请帮忙解决这个问题,先谢谢了。
这是 Jsfiddle:http://jsfiddle.net/sLq3F/456/
最佳答案
您可以使用返回 ReadableStream
的 fetch()
、Response.body.getReader()
、TextDecoder()
、Blob()
、URL.createObjectURL()
。
请注意,在RAM
或可用磁盘空间有限的设备上,在保存文件
对话框中单击保存
后四分零二十秒<4:20
过后,保存文件
对话框关闭,随后又过了 1 分 30 秒1:30
,然后.crdownload
扩展名已从文件管理器 GUI 中的文件中删除。在文件下载到文件系统且“保存文件”对话框可见的第一个 4:20
期间,鼠标指针可移动,但 UI 暂时对单击或操作没有响应。尝试更改选项卡。当“保存文件”对话框关闭并且文件仍在下载到文件系统(扩展名为 .crdownload
)时,UI 将恢复正常功能。
上述过程结束时,文件已成功下载到本地文件系统,总大小为189.8 MB(189,778,220 字节)
。
<!DOCTYPE html>
<html>
<head>
<style>
code {
color:navy;
background-color:#eee;
padding:2px;
}
</style>
</head>
<body>
<button>Request File</button><br>
<progress min="0" max="189778220" value="0"></progress>
<output></output>
<br><br>
<label></label>
<script>
var url = "https://raw.githubusercontent.com/zemirco/sf-city-lots-json/master/citylots.json";
var button = document.querySelector("button");
var progress = document.querySelector("progress");
var label = document.querySelector("label");
var output = document.querySelector("output");
var request = (url) => {
label.innerHTML = `Requesting <code>${url}</code> at ${new Date()}.<br><br>`;
return fetch(url)
.then(response => response.body.getReader())
.then(reader => {
var decoder = new TextDecoder();
var json = "";
label.innerHTML += `Request successful.<br><br>Reading request body at ${new Date()}.<br><br>`;
return reader.read().then(function processData(result) {
if (result.done) {
// do stuff when `reader` is `closed`
return reader.closed.then(function() {
// return `json` string
return json;
});
};
json += decoder.decode(result.value);
output.innerHTML = ` ${json.length} of ${progress.max} bytes read`;
progress.value = json.length;
return reader.read().then(processData)
})
.then(function(data) {
var message = `Reading of <code>${url}</code> complete at ${new Date()}. <br><br>`
+ `${data.length} total bytes read. `
+ `Please allow up to 4 minutes for file to download `
+ `to filesystem after clicking <code>Save</code>.<br><br>`;
label.innerHTML += message;
var blob = new Blob([data], {
type: "application/json"
});
var file = URL.createObjectURL(blob);
var a = document.createElement("a");
a.download = "citylots.json";
a.href = file;
document.body.appendChild(a);
a.click();
var closeBlob = (e) => {
window.removeEventListener("focus", closeBlob);
blob.close();
URL.revokeObjectURL(file);
};
window.addEventListener("focus", closeBlob);
return message.replace(/<[^>]*>/g, "");
})
.catch(function(err) {
console.log("err", err)
})
});
}
var handleRequest = (e) => {
button.setAttribute("disabled", "disabled");
request(url).then(function(message) {
console.log(message);
button.removeAttribute("disabled");
})
};
button.addEventListener("click", handleRequest);
</script>
</body>
</html>
关于javascript - 下载大尺寸json时如何解决Uncaught RangeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39959467/