18

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

1
  • 1
    Welcome to Stack Overflow. You should review the guide for posting good questions. You need to try to solve this problem on your own and then post examples of your own code. Commented Jul 10, 2018 at 19:46

5 Answers 5

29

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

Sign up to request clarification or add additional context in comments.

Comments

16
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>
  )
}

Comments

3

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);
}

Comments

1

A simple way to use FileReader in Reactjs component

To get the content of the file reader in react I used the callback function to update the state as used in the MDN Web docs.

React component

// state to store the base64
const [base64File, setbase64File] = useState(null);

// Create the callback function
const base64Callback = async (err, res) => {
    if (!err) {
      setbase64File(res); // setting the state is the important part 
    } else {
      setbase64File(null);
    }
  };

// call function to convert to base64
getBase64(fileObj, base64Callback);

Function to convert to base64

async function getBase64(file, callback) {
  const reader = new FileReader();
  reader.onload = () => callback(null, reader.result);
  reader.onerror = (error) => callback(error);
  reader.readAsDataURL(file);
}

export default getBase64;

The above code is a modified version of code from the MDN Web docs site click for more

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.