Load a .txt file with input type="file" ...

1

I use the input tag of html and I put the class "file". I edit this function in javascript:

function LoadFile(){
var  text = document.getElementById("inputFile").value;
console.log(text); //"C:\fakepath\exito.txt"

}

and here goes my html:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>save file button and script</title>
  <meta charset="utf-8"/>
  </head>
<body>
<h1>Load File on a Root  </h1>
  <p>Load File</p>
   <input type="file" name="new-image" id="inputFile">
  <button id="loadFile" type="button" onclick="LoadFile()">Load File</button>
   <p>Texto para editar </p>  
  <textarea id="textArea" rows="4" cols="30" style="width:300px;height:600px"></textarea> 
 <script scr="https://cdnjs.cloudflare.com/ajax/libs/cookieconsent2/1.0.9/cookieconsent.min.js"></script>
</body>
</html>

What I want to do is load the text I have in a .txt called "success.txt". I thought I would be able to do it with the method document.getElementById ("inputFile") but I do not know what attribute to get it, if I do .value gives me a path, which should be temporary because C: \ fakepath \ success.txt is not the path where I had the file called "success". My question is What field do I have to put in documentgetElement ... so that I can transfer that value through an assignment operation to the viariable text?

    
asked by Mr. Baldan 23.10.2018 в 09:27
source

1 answer

1

The input type file has a special field called files where you can get the data from the files. But it's not as simple as simply reading that data, you need a FileReader to process the File object:

const input = document.getElementById('file');
const editor = document.getElementById('contenido');
input.addEventListener('change', function () {
  if (input.files.length > 0) {
    readFile(input.files[0]);
  }
});

function readFile(file) {
  const reader = new FileReader();
  reader.onload = function() {
    editor.value= reader.result; 
  }
  reader.readAsText(file);
}
<textarea id="contenido" rows="4" cols="30" style="width:500px;height:300px"></textarea> 

<input type="file" id="file"/>
    
answered by 23.10.2018 в 10:20