Skip to content

Instantly share code, notes, and snippets.

@LarryKlugerDS
Last active October 25, 2020 11:12
Show Gist options
  • Save LarryKlugerDS/de203062dd487c0e7046d3f0ed06e065 to your computer and use it in GitHub Desktop.
Save LarryKlugerDS/de203062dd487c0e7046d3f0ed06e065 to your computer and use it in GitHub Desktop.
openFile handler
/**
* 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