scyrt
scyrt

Reputation: 346

How to use FileReader in React?

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

Upvotes: 18

Views: 99175

Answers (5)

melo
melo

Reputation: 329

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

Upvotes: 1

rixtarbarhar
rixtarbarhar

Reputation: 31

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

Upvotes: 3

Krina Soni
Krina Soni

Reputation: 930

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

Upvotes: 16

Sultan Aslam
Sultan Aslam

Reputation: 6238

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.

Upvotes: -1

Diego Mello
Diego Mello

Reputation: 301

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

Upvotes: 29

Related Questions