将文件作为字符串上传到 JavaScript 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14155310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:51:31  来源:igfitidea点击:

Upload File as String to JavaScript Variable

javascriptfile-uploadjavascript-eventsforms

提问by sissypants

Is there any way for a client to upload a file in an HTML form (e.g. .txt or .csv formats) to a JavaScript variable as a string using only JavaScript? If so, could you provide a simple example? I don't want to use any PHP.

客户端是否可以仅使用 JavaScript 将 HTML 格式(例如 .txt 或 .csv 格式)中的文件作为字符串上传到 JavaScript 变量?如果是这样,你能提供一个简单的例子吗?我不想使用任何 PHP。

Thanks in advance!

提前致谢!

采纳答案by yent

Here is a quick and dirty example based on a form named "myform" that contains a file input named "myfile" :

这是一个基于名为“myform”的表单的快速而肮脏的示例,该表单包含一个名为“myfile”的文件输入:

document.forms['myform'].elements['myfile'].onchange = function(evt) {
    if(!window.FileReader) return; // Browser is not compatible

    var reader = new FileReader();

    reader.onload = function(evt) {
        if(evt.target.readyState != 2) return;
        if(evt.target.error) {
            alert('Error while reading file');
            return;
        }

        filecontent = evt.target.result;

        document.forms['myform'].elements['text'].value = evt.target.result;
    };

    reader.readAsText(evt.target.files[0]);
};

Here's the associated HTML form:

这是相关的 HTML 表单:

<form id="myform">
  <p>
    <input id="myfile" name="files[]" multiple="" type="file" />
    <textarea id="text" rows="20" cols="40">nothing loaded</textarea>
  </p>
</form>

and a jsfiddleto demo it.

和一个jsfiddle来演示它。

回答by ericP

This variation on yent's answermanages multiple uploads and uses jquery:

yent's answer的这种变化管理多个上传并使用jquery:

HTML:

HTML:

<form id="myform">
  <p>
    <input id="myfile" name="files[]" multiple="" type="file" />
    <textarea id="text" rows="20" cols="40">nothing loaded</textarea>
  </p>
</form>

script:

脚本:

$("#myfile").on("change", function (changeEvent) {
  for (var i = 0; i < changeEvent.target.files.length; ++i) {
    (function (file) {               // Wrap current file in a closure.
      var loader = new FileReader();
      loader.onload = function (loadEvent) {
        if (loadEvent.target.readyState != 2)
          return;
        if (loadEvent.target.error) {
          alert("Error while reading file " + file.name + ": " + loadEvent.target.error);
          return;
        }
        console.log(loadEvent.target.result.length); // Your text is in loadEvent.target.result
      };
      loader.readAsText(file);
    })(changeEvent.target.files[i]);
  }
});

Worth noting:

值得注意:

  • You must use one FileReader for each (concurrent) file read. Otherwise you see an exception like The object is already busy reading.
  • The loadEvent callbacks will be called in an arbitrary order, likely dependent on the size of the upload.
  • The loadEvent closure will see the ivalue which ended the loop.
  • FileReader results are NOT arrays; they have no forEach.
  • 您必须为每个(并发)文件读取使用一个 FileReader。否则,您会看到类似The object is already busy reading.
  • loadEvent 回调将以任意顺序调用,可能取决于上传的大小。
  • loadEvent 闭包将看到i结束循环的值。
  • FileReader 结果不是数组;他们没有 forEach。

This jsfiddledemo preserves upload order by laying out divs in the change handler.

这个jsfiddle演示通过在更改处理程序中布置 div 来保留上传顺序。