16

I am trying to let user to "choose text file" and display it in the UI. Later, I'll use the data in *.txt file to plot.

However, I couldn't display the content of txt file.

There are several modules available but I don't know how to make it work in React.

Here are the examples I found:

https://stackoverflow.com/a/40146883/10056318

 jsfiddle.net/0GiS0/nDVYd/

Thanks

imbr
  • 6,226
  • 4
  • 53
  • 65
scyrt
  • 326
  • 1
  • 2
  • 13
  • 1
    Welcome to Stack Overflow. You should review the [guide for posting good questions](https://stackoverflow.com/help/how-to-ask). You need to try to solve this problem on your own and then post examples of your own code. – Logan Bertram Jul 10 '18 at 19:46

4 Answers4

22

I found that code snippet on MDN Documentation, and that solved my problem i am hopping that this could help someone else:

// Callback from a <input type="file" onchange="onChange(event)">
function onChange(event) {
  var file = event.target.files[0];
  var reader = new FileReader();
  reader.onload = function(event) {
    // The file's text will be printed here
    console.log(event.target.result)
  };

  reader.readAsText(file);
}

More informations at https://developer.mozilla.org/pt-BR/docs/Web/API/FileReader/onload

Diego Mello
  • 231
  • 2
  • 6
12
handleFile = (e) => {
  const content = e.target.result;
  console.log('file content',  content)
  // You can set content in state and show it in render.
}

handleChangeFile = (file) => {
  let fileData = new FileReader();
  fileData.onloadend = handleFile;
  fileData.readAsText(file);
}

render(){
  return(
     <div>
        <input type="file" accept=".txt" onChange={e => 
            handleChangeFile(e.target.files[0])} /> 
     </div>
  )
}
Priyanka
  • 127
  • 1
  • 1
  • 11
Krina Soni
  • 870
  • 6
  • 14
1

hey this copying and paste is okay.. but these answers dont refer to state. also using reading data as url is easier for an img tag

    function onChange(event) {
  var file = event.target.files[0];
  var reader = new FileReader();
  reader.onload = function(event) {
    // The file's text will be printed here
    SET STATE HERE FOR URL!!!!
    
  };

  reader.readAsDataURL(file);
}
-1

Install react-file-reader (A flexible ReactJS component for handling styled HTML file inputs.)

Simple Example

import ReactFileReader from 'react-file-reader';

class Dashboard extends Component {
  state = {
    file : ""
  }

  handleFiles = files => {
    this.setState({
      file: files.base64
    })
  }
  render() {
    return(
      <div className="files">
        <ReactFileReader handleFiles={this.handleFiles}>
          <button className='btn'>Upload</button>
        </ReactFileReader>

        <p>Read</p>
        <iframe src={this.state.file} frameBorder="0" height="400" width="50%" />
      </div>
    )
  }
}

Update Answer: This repository has been archived by the owner. It is now read-only.

Sultan Aslam
  • 5,600
  • 2
  • 38
  • 44