我编写了一个d3脚本,该脚本绘制了一些数据,并且在其中硬编码了输入文件的路径。
我希望能够通过在计算机上浏览然后将其传递给脚本来选择文件。
<body>
<!--locally browse to get the filename-->
<input type="file" id="input">
<script src="http://d3js.org/d3.v3.js"></script>
<script>
// Get the data
d3.tsv("#input", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
// then the code that plots etc....
</script>
</html>
最佳答案
1)创建输入选择按钮并将其注册到文件选择处理程序函数:
var input = d3.select("body").append("input")
.attr("type","file")
.on("change", handleFileSelect)
2)文件选择处理程序将向fileHandler注册一个新函数,作为onload回调上的输入:
// Single file handler
function handleFileSelect() {
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
} else {
alert('The File APIs are not fully supported in this browser.');
}
var f = event.target.files[0]; // FileList object
var reader = new FileReader();
reader.onload = function(event) {
load_d3(event.target.result)
};
// Read in the file as a data URL.
reader.readAsDataURL(f);
}
3)创建一个以fileHandler作为输入的函数,该函数调用您的D3代码(在此示例中为d3.json。您可以将其改编为tsv)
function load_d3(fileHandler) {
d3.json(fileHandler, function(error, root) {
//do stuff
};
};
希望这可以帮助。
关于javascript - 如何在HTML中获取文件名并在D3.js(javascript)中使用它?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28584548/