Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use FileReader in React?

Tags:

reactjs

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

like image 761
scyrt Avatar asked Jul 10 '18 18:07

scyrt


People also ask

What is FileReader in React JS?

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.

How do I fetch images from API in React?

To fetch image from API with React, we can use the fetch function. We call fetch with the imageUrl to make a GET request to it. Then we call res. blob to convert the response object to a blob.

How do I load a file into React?

preventDefault() const url = 'http://localhost:3000/uploadFile'; const formData = new FormData(); formData. append('file', file); formData. append('fileName', file.name); const config = { headers: { 'content-type': 'multipart/form-data', }, }; axios. post(url, formData, config).


2 Answers

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

like image 194
Diego Mello Avatar answered Sep 30 '22 14:09

Diego Mello


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>
  )
}
like image 42
Krina Soni Avatar answered Sep 30 '22 13:09

Krina Soni