Вам не нужен полный путь к файлу, чтобы прочитать его содержимое, и я уверен, что d3 позволяет вам предоставлять данные напрямую, а не считывать их из «файла» (предположительно, это действительно из URL).
Просто прочитайте его с FileReader
.Например, в обработчике change
на input type="file"
:
var file = theInput.files[0];
var fr = new FileReader();
fr.onload = function() {
// Use fr.result here, it's a string of the file's contents.
// If it's JSON and you want the data in the form `d3.json` would have
// provided it, do: `var data = JSON.parse(fr.result);`
// and then use `data`.
};
fr.readAsText(file);
Live Example (просто чтение файла, а не передача данных в d3):
document.querySelector("input[type=file]").addEventListener("change", function() {
var file = this.files[0];
var fr = new FileReader();
fr.onload = function() {
console.log("Done");
var pre = document.getElementById("output");
pre.innerHTML = "";
pre.appendChild(
document.createTextNode(fr.result)
);
};
fr.onerror = function() {
console.log("Error reading the file");
};
console.log("Reading...");
fr.readAsText(file);
});
pre {
border: 1px solid black;
padding: 2px;
}
Contents: