Files and data
Read a user-selected text file in the browser
Use a file input and File.text to read a file the user deliberately selected. Validate size and parse errors before displaying imported content.
Worked example
HTML example · save as example.html and open in a browser
<label for="file">Choose a small JSON file</label>
<input id="file" type="file" accept=".json,application/json">
<pre id="result"></pre>
<script>
document.querySelector('#file').addEventListener('change', async event => {
const file = event.target.files[0];
const output = document.querySelector('#result');
if (!file) return;
try {
if (file.size > 1024 * 1024) throw new Error('Choose a file smaller than 1 MiB');
output.textContent = JSON.stringify(JSON.parse(await file.text()), null, 2);
} catch (error) { output.textContent = error.message; }
});
</script>How it works
The browser grants access to the selected File object, not arbitrary filesystem paths. The example reads and parses only after a size check, then writes textContent so imported markup is not executed as HTML.
Limits and mistakes
Accept is a picker hint rather than validation. A script on the page can still transmit selected contents if written to do so; the presence of a file input is not a privacy guarantee. Inspect application behavior and network requests when evaluating a tool.
Check the result
Try valid JSON, malformed JSON, a canceled selection, and an oversized fixture. Confirm the result is readable and no raw imported value is inserted with innerHTML.
Sources
Reference documentation for the behavior used in this guide: