在各种浏览器中使用javascript在客户端读取文件内容

Dam*_*isa 96 html javascript file-io sandbox

我正在尝试提供一个仅限脚本的解决方案,用于通过浏览器读取客户端计算机上的文件内容.

我有一个适用于Firefox和Internet Explorer的解决方案.它不漂亮,但我现在只是在尝试:

function getFileContents() {
    var fileForUpload = document.forms[0].fileForUpload;
    var fileName = fileForUpload.value;

    if (fileForUpload.files) {
        var fileContents = fileForUpload.files.item(0).getAsBinary();
        document.forms[0].fileContents.innerHTML = fileContents;
    } else {
        // try the IE method
        var fileContents = ieReadFile(fileName);
        document.forms[0].fileContents.innerHTML = fileContents;
    }
}       

function ieReadFile(filename) 
{
    try
    {
        var fso  = new ActiveXObject("Scripting.FileSystemObject"); 
        var fh = fso.OpenTextFile(filename, 1); 
        var contents = fh.ReadAll(); 
        fh.Close();
        return contents;
    }
    catch (Exception)
    {
        return "Cannot open file :(";
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以打电话getFileContents(),它会将内容写入fileContents文本区域.

有没有办法在其他浏览器中执行此操作?

我目前最关心的是Safari和Chrome,但我愿意接受任何其他浏览器的建议.

编辑:回答问题,"你为什么要这样做?":

基本上,我想在客户端将文件内容与一次性密码一起散列,以便我可以将此信息作为验证发回.

Bri*_*ell 131

已编辑以添加有关File API的信息

自从我最初写这个答案以来,File API已被提议作为标准并在大多数浏览器中实现(从IE 10开始,它增加了FileReader对这里描述的API的支持,但还不是FileAPI).API比旧的Mozilla API复杂一点,因为它旨在支持异步读取文件,更好地支持二进制文件和解码不同的文本编码.有Mozilla开发者网络上提供的一些文件以及各种在线的例子.您可以按如下方式使用它:

var file = document.getElementById("fileForUpload").files[0];
if (file) {
    var reader = new FileReader();
    reader.readAsText(file, "UTF-8");
    reader.onload = function (evt) {
        document.getElementById("fileContents").innerHTML = evt.target.result;
    }
    reader.onerror = function (evt) {
        document.getElementById("fileContents").innerHTML = "error reading file";
    }
}
Run Code Online (Sandbox Code Playgroud)

原始答案

似乎没有办法在WebKit中执行此操作(因此,Safari和Chrome).File对象拥有的唯一键是fileNamefileSize.根据File和FileList支持的提交消息,这些都受到Mozilla的File对象的启发,但它们似乎只支持一部分功能.

如果您想更改此设置,您可以随时 WebKit项目发送补丁.另一种可能性是建议将Mozilla API包含在HTML 5中 ; 在WHATWG的邮件列表是可能做到这一点的最好的地方.如果你这样做,那么很可能会有一种跨浏览器的方式来做到这一点,至少在几年后.当然,提交补丁或提案以包含在HTML 5中确实意味着一些工作可以捍卫这个想法,但Firefox已经实现它的事实为您提供了一些开始.

  • 它不会破坏浏览器沙箱,因为您故意选择上传该文件; 如果它可以到达服务器,它可以返回浏览器,只需额外的往返.鉴于使离线模式适用于Web应用程序的工作,这将是一个合理的功能. (4认同)
  • 在调用 `readAsText` 之前不应该附加事件处理程序吗? (2认同)

cdi*_*ins 19

要使用文件打开对话框读取用户选择的文件,您可以使用该<input type="file">标记.您可以从MSDN上找到有关它的信息.选择文件后,您可以使用FileReader API读取内容.

function onFileLoad(elementId, event) {
    document.getElementById(elementId).innerText = event.target.result;
}

function onChooseFile(event, onLoadFileHandler) {
    if (typeof window.FileReader !== 'function')
        throw ("The file API isn't supported on this browser.");
    let input = event.target;
    if (!input)
        throw ("The browser does not properly implement the event object");
    if (!input.files)
        throw ("This browser does not support the `files` property of the file input.");
    if (!input.files[0])
        return undefined;
    let file = input.files[0];
    let fr = new FileReader();
    fr.onload = onLoadFileHandler;
    fr.readAsText(file);
}
Run Code Online (Sandbox Code Playgroud)
<input type='file' onchange='onChooseFile(event, onFileLoad.bind(this, "contents"))' />
<p id="contents"></p>
Run Code Online (Sandbox Code Playgroud)


wol*_*yst 7

有一个现代的本地替代方案:File实现Blob,所以我们可以调用Blob.text()

async function readText(event) {
  const file = event.target.files.item(0)
  const text = await file.text();
  
  document.getElementById("output").innerText = text
}
Run Code Online (Sandbox Code Playgroud)
<input type="file" onchange="readText(event)" />
<pre id="output"></pre>
Run Code Online (Sandbox Code Playgroud)

目前(2020 年 9 月)Chrome 和 Firefox 支持此功能,对于其他浏览器,您需要加载 polyfill,例如blob-polyfill

  • 现在所有主要浏览器都支持 - https://caniuse.com/mdn-api_blob_text (2认同)

Mny*_*kka 5

快乐编码!
如果您在 Internet Explorer 上收到错误,请更改安全设置以允许 ActiveX

var CallBackFunction = function(content) {
  alert(content);
}
ReadFileAllBrowsers(document.getElementById("file_upload"), CallBackFunction);
//Tested in Mozilla Firefox browser, Chrome
function ReadFileAllBrowsers(FileElement, CallBackFunction) {
  try {
    var file = FileElement.files[0];
    var contents_ = "";

    if (file) {
      var reader = new FileReader();
      reader.readAsText(file, "UTF-8");
      reader.onload = function(evt) {
        CallBackFunction(evt.target.result);
      }
      reader.onerror = function(evt) {
        alert("Error reading file");
      }
    }
  } catch (Exception) {
    var fall_back = ieReadFile(FileElement.value);
    if (fall_back != false) {
      CallBackFunction(fall_back);
    }
  }
}
///Reading files with Internet Explorer
function ieReadFile(filename) {
  try {
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile(filename, 1);
    var contents = fh.ReadAll();
    fh.Close();
    return contents;
  } catch (Exception) {
    alert(Exception);
    return false;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • [Acxtive X 现在(谢天谢地)死了](https://blogs.windows.com/msedgedev/2015/05/06/a-break-from-the-past-part-2-saying-goodbye-to-activex -vbscript-attachevent/) (9认同)