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
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.
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.
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).
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
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>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With