临时上传文件以使用它 - javascript

Zah*_*idi 0 html javascript file-upload d3.js

我正在尝试获取通过拖放检索的文件的完整路径。但问题是,出于安全原因,浏览器不允许这样做..:'(

所以我的问题是:

是否可以在拖放文件时,在使用期间将其在线上传,所以暂时(因为我使用 d3.json 来恢复文件,它允许我在线恢复 json 文件..),并删除在线文件文件在使用结束时,也就是说在关闭选项卡时?

再次感谢您的帮助。

T.J*_*der 5

您不需要文件的完整路径来读取其内容,而且我确信 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);
Run Code Online (Sandbox Code Playgroud)

现场示例(仅读取文件,不将数据传递给 d3):

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);
Run Code Online (Sandbox Code Playgroud)
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);
});
Run Code Online (Sandbox Code Playgroud)
pre {
  border: 1px solid black;
  padding: 2px;
}
Run Code Online (Sandbox Code Playgroud)