Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - Reading uploaded text file contents in html

I want to show contents of uploaded file in html, I can just upload a text file. My 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

question from:https://stackoverflow.com/questions/31746837/reading-uploaded-text-file-contents-in-html

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...