Last active
October 25, 2020 11:12
-
-
Save LarryKlugerDS/de203062dd487c0e7046d3f0ed06e065 to your computer and use it in GitHub Desktop.
openFile handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* The file input element | |
*/ | |
<input type="file" className="hidden" | |
multiple={false} | |
accept=".json,.csv,.txt,.text,application/json,text/csv,text/plain" | |
onChange={evt => this.openFile(evt)} | |
/> | |
/** | |
* The file input onChange handler | |
* Process the file within the React app. We're NOT uploading it to the server! | |
*/ | |
openFile(evt) { | |
let status = []; // Status output | |
const fileObj = evt.target.files[0]; // We've not allowed multiple files. | |
// See https://developer.mozilla.org/en-US/docs/Web/API/FileReader | |
const reader = new FileReader(); | |
// Defining the function here gives it access to the fileObj constant. | |
let fileloaded = e => { | |
// e.target.result is the file's content as text | |
// Don't trust the fileContents! | |
// Test any assumptions about its contents! | |
const fileContents = e.target.result; | |
status.push(`File name: "${fileObj.name}". ` + | |
`Length: ${fileContents.length} bytes.`); | |
// Show first 80 characters of the file | |
const first80char = fileContents.substring(0,80); | |
status.push (`First 80 characters of the file:\n${first80char}`) | |
// Show the status messages | |
this.setState ({status: status.join("\n")}); | |
} | |
// Mainline of the method | |
fileloaded = fileloaded.bind(this); | |
// The fileloaded event handler is triggered when the read completes | |
reader.onload = fileloaded; | |
reader.readAsText(fileObj); // read the file | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment