Javascript 在html中读取上传的文本文件内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31746837/
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-08-23 07:07:21  来源:igfitidea点击:

Reading uploaded text file contents in html

javascripthtmlfilefile-upload

提问by Gürkan ?atak

I want to show contents of uploaded file in html, I can just upload a text file. My example.html:

我想在html中显示上传文件的内容,我可以上传一个文本文件。我的example.html:

<html xmlns="http://www.w3.org/1999/xhtml" >
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>

<textarea id="2" name="y" style="width:400px;height:150px;"></textarea>
</html>

How can I show contents of any uploaded text file in textarea shown below? ScreenShot

如何在如下所示的 textarea 中显示任何上传的文本文件的内容? 截屏

回答by terales

I've came here from google and was surprised to see no working example.

我从谷歌来到这里,惊讶地看到没有工作示例。

You can read files with FileReader APIwith good cross-browser support.

您可以使用具有良好跨浏览器支持的FileReader API读取文件。

const reader = new FileReader()
reader.onload = event => console.log(event.target.result) // desired file content
reader.onerror = error => reject(error)
reader.readAsText(file) // you could also read images and other binaries

See fully working example below.

请参阅下面的完整工作示例。

document.getElementById('input-file')
  .addEventListener('change', getFile)

function getFile(event) {
 const input = event.target
  if ('files' in input && input.files.length > 0) {
   placeFileContent(
      document.getElementById('content-target'),
      input.files[0])
  }
}

function placeFileContent(target, file) {
 readFileContent(file).then(content => {
   target.value = content
  }).catch(error => console.log(error))
}

function readFileContent(file) {
 const reader = new FileReader()
  return new Promise((resolve, reject) => {
    reader.onload = event => resolve(event.target.result)
    reader.onerror = error => reject(error)
    reader.readAsText(file)
  })
}
label {
  cursor: pointer;
}

textarea {
  width: 400px;
  height: 150px;
}
<div>
 <label for="input-file">Specify a file:</label><br>
 <input type="file" id="input-file">
</div>

<textarea id="content-target"></textarea>

回答by app

Here's one way:

这是一种方法:

HTML

HTML

<tr>
    <td>Select a File to Load:</td>
    <td><input type="file" id="fileToLoad"></td>
    <td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>

JavaScript

JavaScript

function loadFileAsText(){
  var fileToLoad = document.getElementById("fileToLoad").files[0];

  var fileReader = new FileReader();
  fileReader.onload = function(fileLoadedEvent){
      var textFromFileLoaded = fileLoadedEvent.target.result;
      document.getElementById("inputTextToSave").value = textFromFileLoaded;
  };

  fileReader.readAsText(fileToLoad, "UTF-8");
}

回答by aks007

document.getElementById('input-file')
  .addEventListener('change', getFile)

function getFile(event) {
 const input = event.target
  if ('files' in input && input.files.length > 0) {
   placeFileContent(
      document.getElementById('content-target'),
      input.files[0])
  }
}

function placeFileContent(target, file) {
 readFileContent(file).then(content => {
   target.value = content
  }).catch(error => console.log(error))
}

function readFileContent(file) {
 const reader = new FileReader()
  return new Promise((resolve, reject) => {
    reader.onload = event => resolve(event.target.result)
    reader.onerror = error => reject(error)
    reader.readAsText(file)
  })
}
label {
  cursor: pointer;
}

textarea {
  width: 400px;
  height: 150px;
}
<div>
 <label for="input-file">Specify a file:</label><br>
 <input type="file" id="input-file">
</div>

<textarea id="content-target"></textarea>

回答by Shrinivas Pai

Try this.

尝试这个。

HTML

HTML

<p>
Please specify a file, or a set of files:<br>
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
</p>

<textarea id="demo" style="width:400px;height:150px;"></textarea>

JS

JS

function myFunction(){
    var x = document.getElementById("myFile");
    var txt = "";
    if ('files' in x) {
        if (x.files.length == 0) {
            txt = "Select one or more files.";
        } else {
            for (var i = 0; i < x.files.length; i++) {
                txt += (i+1) + ". file";
                var file = x.files[i];
                if ('name' in file) {
                    txt += "name: " + file.name + "";
                }
                if ('size' in file) {
                    txt += "size: " + file.size + " bytes ";
                }
            }
        }
    } 
    else {
        if (x.value == "") {
            txt += "Select one or more files.";
        } else {
            txt += "The files property is not supported by your browser!";
            txt  += "The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead. 
        }
    }
    document.getElementById("demo").innerHTML = txt;
}

Demo

演示