This example program demonstrates how to use a create a synthetic file object or choose a file and read and display its contents in JavaScript.
<!DOCTYPE html> <html> <head> <title>XoaX.net's Javascript</title> <script type="text/javascript" src="CreateSelectSyntheticFile.js"></script> </head> <body onload="Initialize()"> <input type="file" id="idFileInput" multiple> <p id="idContents"></p> </body> </html>
function Initialize() {
// File in the data with a synthetic file data.
const saFileContent = ['5.3 9.86 4.17 4.92 3.03 15.55 13.27 5.68 7.2 6.06 5.68 5.68 6.06'];
const sFileName = 'SomeFileName.txt';
// Create a local file object with some content
const qFile = new File(saFileContent, sFileName);
// Create a file reader
const kqFileReader = new FileReader();
// Add an event listener for loading the file
kqFileReader.addEventListener("load", () => {
const kqContentElement = document.getElementById('idContents');
kqContentElement.innerHTML = kqFileReader.result;
});
// Read the file
kqFileReader.readAsText(qFile);
// File in the element with data from a selected file.
// Get the input element
const kqInputElement = document.getElementById('idFileInput');
// Add an event listener for the change event
kqInputElement.addEventListener('change', (qEvent) => {
const qFileList = qEvent.target.files;
// Use this for any selected file
const kqSelectedFileReader = new FileReader();
// Add an event listener for loading the file
kqSelectedFileReader.addEventListener("load", () => {
const kqContentElement = document.getElementById('idContents');
kqContentElement.innerHTML = kqSelectedFileReader.result;
});
// Read the file
kqSelectedFileReader.readAsText(qFileList[0]);
});
const qDataTransfer = new DataTransfer();
// Add the file to the list of the transfer object
qDataTransfer.items.add(qFile);
// Set the files of the input element to the file list
kqInputElement.files = qDataTransfer.files;
}
© 20072025 XoaX.net LLC. All rights reserved.