Tag Archives: open file
JavaScript || FileIO.js – Open, Save, & Read Local & Remote Files Using Vanilla JavaScript

The following is a module that handles opening, reading, and saving files in JavaScript. This allows for file manipulation on the client side.
Contents
1. Open File Dialog
2. Reading Files
3. Saving Files
4. Reading Remote URL Files
5. Saving Remote URL Files
6. FileIO.js Namespace
7. More Examples
1. Open File Dialog
Syntax is very straightforward. The following demonstrates opening a file dialog to get files from the user.
12345678910111213141516
// Open a file dialog prompt to select files. <script>(async () => { // An array of File objects is returned. let files = await FileIO.openDialog({ contentTypes: '.json, text/csv, image/*', // Optional. The accepted file types allowMultiple: true, // Optional. Allows multiple file selection. Default is false }); // ... Do something with the selected files files.forEach((file, index) => { console.log(`File #${index + 1}: ${file.name}`); });})();</script>
‘FileIO.openDialog‘ returns an array of File objects that contains the selected files after the user hits submit. You can specify the accepted file types, as well as if selecting multiple files is allowed or not.
2. Reading Files
The following example demonstrates how to read a file. This allows to read file contents.
123456789101112131415161718192021
// Read file contents. <script>(async () => { // By default, file data is read as text. // To read a file as a Uint8Array, // set 'readAsTypedArray' to true let contents = await FileIO.read({ data: file, // File/Blob encoding: 'ISO-8859-1', // Optional. If reading as text, set the encoding. Default is UTF-8 readAsTypedArray: false, // Optional. Specifies to read the file as a Uint8Array. Default is false onProgressChange: (progressEvent) => { // Optional. Fires periodically as the file is read let percentLoaded = Number(((progressEvent.loaded / progressEvent.total) * 100).toFixed(2)); console.log(`Percent Loaded: ${percentLoaded}`); } }); // ... Do something with the file contents console.log(contents);})();</script>
‘FileIO.read‘ accepts either a File, or a Blob as acceptable data to be read.
By default, ‘FileIO.read‘ will read the file contents as text. To read file contents as an array, set the property ‘readAsTypedArray‘ to true. A Uint8Array is returned when this option is set to true.
3. Saving Files
The following example demonstrates how to create and save a file. This allows to save contents to a file.
12345678910111213141516171819202122232425
// Save data to a file. <script>(() => { let text = 'My Programming Notes is awesome!'; let filename = 'myProgrammingNotes.txt' // The data to be saved can be a String/Blob/File/Uint8Array let data = text; // Example demonstrating the other datatypes that can be saved //data = new Blob([text], {type: "text/plain;charset=utf-8"}); //data = new File([text], filename, {type: "text/plain;charset=utf-8"}); //data = FileIO.stringToTypedArray(text); // Save the data to a file FileIO.save({ data: data, // String/Blob/File/Uint8Array filename: filename, // Optional if data is a File object decodeBase64Data: false, // Optional. If data is a base64 string, specifies if it should be decoded before saving. Default is false. }); // ... The file is saved to the client})();</script>
‘FileIO.save‘ accepts either a String, Blob, File, or a Uint8Array as acceptable data to be saved.
If the data to be saved is a base64 string, set the property ‘decodeBase64Data‘ to true in order to decode the string before saving. If the bease64 string is a file, this will allow the actual file to be decoded and saved to the client. Note: This action is only performed if the data to be saved is a string.
4. Reading Remote URL Files
The following example demonstrates how ‘FileIO.read‘ can be used to read downloaded file contents from a remote URL.
1234567891011121314151617181920212223242526
// Read file contents from a remote URL. <script>(async () => { // Remote file url let url = 'https://www.w3.org/TR/PNG/iso_8859-1.txt'; // Other example files //url = 'http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv'; //url = 'http://dummy.restapiexample.com/api/v1/employees'; // Fetch the URL let response = await fetch(url); // Get the response file data let blob = await response.blob(); // Read the remote file as text let contents = await FileIO.read({ data: blob }); // ... Do something with the file contents console.log(contents);})();</script>
The example above uses fetch to retrieve data from the remote URL. Once the data is received, ‘FileIO.read‘ can be used to read its file contents.
5. Saving Remote URL Files
The following example demonstrates how ‘FileIO.save‘ can be used to save downloaded file contents from a remote URL to the client.
1234567891011121314151617181920212223242526272829
// Save file contents from a remote URL. <script>(async () => { // Remote file url let url = 'https://www.w3.org/TR/PNG/iso_8859-1.txt'; // Other example files //url = 'https://www.nba.com/lakers/sites/lakers/files/lakers_logo_500.png'; //url = 'http://www.africau.edu/images/default/sample.pdf'; //url = 'https://gahp.net/wp-content/uploads/2017/09/sample.pdf' //url = 'http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv'; //url = 'https://file-examples-com.github.io/uploads/2017/02/file-sample_1MB.docx'; // Fetch the URL let response = await fetch(url); // Get the response file data let blob = await response.blob(); // Save the remote file to the client FileIO.save({ data: blob, filename: FileIO.getFilename(url) }); // ... The file is saved to the client})();</script>
The example above uses fetch to retrieve data from the remote URL. Once the data is received, ‘FileIO.save‘ can be used to save its file contents.
6. FileIO.js Namespace
The following is the FileIO.js Namespace. Include this in your project to start using!
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
// ============================================================================// Author: Kenneth Perkins// Date: Jul 17, 2020// Taken From: http://programmingnotes.org/// File: FileIO.js// Description: Namespace which handles opening, reading and saving files// Example:// // 1. Save data to a file// FileIO.save({// data: 'My Programming Notes is awesome!',// filename: 'notes.txt',// decodeBase64Data: false, // optional// });//// // 2. Get files// let files = await FileIO.openDialog({// contentTypes: '.txt, .json, .doc, .png', // optional// allowMultiple: true, // optional// });//// // 3. Read file contents// let contents = await FileIO.read({// data: file,// encoding: 'UTF-8', // optional// readAsTypedArray: false, // optional// });// ============================================================================/*** NAMESPACE: FileIO* USE: Handles opening, reading and saving files.*/var FileIO = FileIO || {};(function(namespace) { 'use strict'; // -- Public data -- // Property to hold public variables and functions let exposed = namespace; /** * FUNCTION: save * USE: Exports data to be saved to the client * @param options: An object of file save options. * Its made up of the following properties: * { * data: The data (String/Blob/File/Uint8Array) to be saved. * filename: Optional. The name of the file * decodeBase64Data: Optional. If the data to be saved is not * a Blob type, it will be converted to one. If the data * being converted is a base64 string, this specifies * if the string should be decoded or not when converting * to a Blob. * } * @return: N/A. */ exposed.save = (options) => { if (isNull(options)) { throw new TypeError('There are no options specified'); } else if (isNull(options.data)) { throw new TypeError('There is no data is specified to save'); } let blob = options.data; let decodeBase64Data = options.decodeBase64Data || false; // Check to see if the file data is a blob. // Try to convert it if not if (!isBlob(blob)) { blob = exposed.convertToBlob(blob, decodeBase64Data); } let filename = options.filename || blob.name || 'FileIO_Download'; let urlCreator = window.URL || window.webkitURL; let url = urlCreator.createObjectURL(blob); let a = document.createElement('a'); a.download = filename; a.href = url; a.style.display = 'none'; a.rel = 'noopener'; a.target = '_blank'; document.body.appendChild(a); elementClick(a); setTimeout(() => { document.body.removeChild(a); urlCreator.revokeObjectURL(url) }, 250); } /** * FUNCTION: openDialog * USE: Opens a file dialog box which enables the user to select a file * @param options: An object of file dialog options. * Its made up of the following properties: * { * contentTypes: Optional. A comma separated string of * acceptable content types. * allowMultiple: Optional. Boolean indicating if the user * can select multple files. Default is false. * } * @return: A promise that returns the selected files when the user hits submit. */ exposed.openDialog = (options) => { return new Promise((resolve, reject) => { try { if (isNull(options)) { options = {}; } // Check to see if content types is an array let contentTypes = options.contentTypes || ''; if (!isNull(contentTypes) && !Array.isArray(contentTypes)) { contentTypes = contentTypes.split(','); } if (!isNull(contentTypes)) { contentTypes = contentTypes.join(','); } let input = document.createElement('input'); input.type = 'file'; input.multiple = options.allowMultiple || false; input.accept = contentTypes; input.addEventListener('change', (e) => { // Convert FileList to an array let files = Array.prototype.slice.call(input.files); resolve(files); }); input.style.display = 'none'; document.body.appendChild(input); elementClick(input); setTimeout(() => { document.body.removeChild(input); }, 250); } catch (e) { let message = e.message ? e.message : e; reject(`Failed to open dialog. Reason: ${message}`); } }); } /** * FUNCTION: read * USE: Reads a file and gets its file contents * @param options: An object of file read options. * Its made up of the following properties: * { * data: The data (File/Blob) to be read. * encoding: Optional. String that indicates the file encoding * when opening a file while reading as text. Default is UTF-8. * readAsText is the default behavior. * readAsTypedArray: Optional. Boolean that indicates if the file should * be read as a typed array. If this option is specified, a Uint8Array * object is returned on file read. * onProgressChange(progressEvent): Function that is fired periodically as * the FileReader reads data. * } * @return: A promise that returns the file contents after successful file read. */ exposed.read = (options) => { return new Promise((resolve, reject) => { try { if (!(window && window.File && window.FileList && window.FileReader)) { throw new TypeError('Unable to read. Your environment does not support File API.'); } else if (isNull(options)) { // Check to see if there are options throw new TypeError('There are no options specified.'); } else if (isNull(options.data)) { // Check to see if a file is specified throw new TypeError('Unable to read. There is no data specified.'); } else if (!isBlob(options.data)) { // Check to see if a file is specified throw new TypeError(`Unable to read data of type: ${typeof options.data}. Reason: '${options.data}' is not a Blob/File.`); } else if (!isNull(options.onProgressChange) && !isFunction(options.onProgressChange)) { // Check to see if progress change callback is a function throw new TypeError(`Unable to call onProgressChange of type: ${typeof options.onProgressChange}. Reason: '${options.onProgressChange}' is not a function.`); } let file = options.data; let encoding = options.encoding || 'UTF-8'; let readAsTypedArray = options.readAsTypedArray || false; // Setting up the reader let reader = new FileReader(); // Tell the reader what to do when it's done reading reader.addEventListener('load', (e) => { let content = e.target.result; if (readAsTypedArray) { content = new Uint8Array(content) } resolve(content); }); // Return the error reader.addEventListener('error', (e) => { reject(reader.error); }); // Call the on progress change function if specified if (options.onProgressChange) { let events = ['loadstart', 'loadend', 'progress']; events.forEach((eventName) => { reader.addEventListener(eventName, (e) => { options.onProgressChange.call(this, e); }); }); } // Begin reading the file if (readAsTypedArray) { reader.readAsArrayBuffer(file); } else { reader.readAsText(file, encoding); } } catch (e) { let message = e.message ? e.message : e; reject(`Failed to read data. Reason: ${message}`); } }); } /** * FUNCTION: convertToBlob * USE: Converts data to a Blob * @param data: Data to be converted to a Blob. * @param decodeBase64Data: Indicates if the data should be base64 decoded. * @return: The data converted to a Blob. */ exposed.convertToBlob = (data, decodeBase64Data = false) => { let arry = data; if (!isTypedArray(arry)) { arry = decodeBase64Data ? exposed.base64ToTypedArray(data) : exposed.stringToTypedArray(data); } let blob = new Blob([arry]); return blob; } /** * FUNCTION: stringToTypedArray * USE: Converts a string to a typed array (Uint8Array) * @param data: String to be converted to a typed array. * @return: The data converted to a typed array. */ exposed.stringToTypedArray = (data) => { let arry = new Uint8Array(data.length); for (let index = 0; index < data.length; ++index) { arry[index] = data.charCodeAt(index); } return arry; } /** * FUNCTION: typedArrayToString * USE: Converts a typed array to a string * @param data: Typed array to be converted to a string. * @return: The data converted to a string. */ exposed.typedArrayToString = (data) => { let str = ''; for (let index = 0; index < data.length; ++index) { str += String.fromCharCode(data[index]); } return str; } /** * FUNCTION: base64ToTypedArray * USE: Converts a base64 string to a typed array * @param data: Base64 string to be converted to a typed array. * @return: The data converted to a typed array. */ exposed.base64ToTypedArray = (data) => { let str = atob(data); let arry = exposed.stringToTypedArray(str); return arry; } /** * FUNCTION: typedArrayToBase64 * USE: Converts a typed array to a base64 string * @param data: Typed array to be converted to a base64 string. * @return: The data converted to a base64 string. */ exposed.typedArrayToBase64 = (data) => { let str = exposed.typedArrayToString(data); return btoa(str); } /** * FUNCTION: getFilename * USE: Returns the filename of a url * @param url: The url. * @return: The filename of a url. */ exposed.getFilename = (url) => { let filename = ''; if (url && url.length > 0) { filename = url.split('\\').pop().split('/').pop(); // Remove any querystring if (filename.indexOf('?') > -1) { filename = filename.substr(0, filename.indexOf('?')); } } return filename; } /** * FUNCTION: getExtension * USE: Returns the file extension of the filename of a url * @param url: The url. * @return: The file extension of a url. */ exposed.getExtension = (url) => { let filename = exposed.getFilename(url); let ext = filename.split('.').pop(); return (ext === filename) ? '' : ext; } // -- Private data -- let isTypedArray = (item) => { return item && ArrayBuffer.isView(item) && !(item instanceof DataView); } let isBlob = (item) => { return item instanceof Blob; } let isNull = (item) => { return undefined === item || null === item } let isFunction = (item) => { return 'function' === typeof item } let elementClick = (element) => { try { element.dispatchEvent(new MouseEvent('click')) } catch (e) { let evt = document.createEvent('MouseEvents') evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null) element.dispatchEvent(evt) } } (function (factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } }(function() { return namespace; }));}(FileIO)); // http://programmingnotes.org/
7. More Examples
Below are more examples demonstrating the use of ‘FileIO.js‘. Don’t forget to include the module when running the examples!
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
<!--// ============================================================================// Author: Kenneth Perkins// Date: Jul 17, 2020// Taken From: http://programmingnotes.org/// File: fileIODemo.html// Description: Demonstrates the use of FileIO.js// ============================================================================--><!DOCTYPE html><html><head><meta charset="utf-8"/><title>My Programming Notes FileIO.js Demo</title><style>.main { text-align:center; margin-left:auto; margin-right:auto;} .button { padding: 5px; background-color: #d2d2d2; height:100%; text-align:center; text-decoration:none; color:black; display: flex; justify-content: center; align-items: center; flex-direction: column; border-radius: 15px; cursor: pointer; width: 120px;} .button:hover { background-color:#bdbdbd;} .inline { display:inline-block;} .image-section, .text-section, .video-section { width: 60%; vertical-align: text-top; margin: 15px;} .imageContainer, .textContainer, .videoContainer { text-align: left; min-height: 100px; max-height: 350px; overflow: auto;} .text-section { width: 30%;} .textContainer { border: 1px solid black; padding: 10px;} .video-section { width: 100%;} .videoContainer { text-align: center;} .fileStatus { margin: 10px; display: none;}</style> <!-- // Include module --><script type="text/javascript" src="./FileIO.js"></script> </head><body><div class="main"> My Programming Notes FileIO.js Demo <div style="margin: 10px;"> <div id="btnOpenFile" class="inline button"> Open File </div> <div class="fileStatus"> </div> </div> <hr /> <div class="inline image-section" > Images: <div class="imageContainer"></div> </div> <div class="inline text-section"> Text: <div class="textContainer"></div> <div style="margin: 10px;"> <div id="btnSaveText" class="inline button"> Save Text </div> </div> </div> <div class="video-section"> Video: <div class="videoContainer"></div> </div></div> <script>// Open a file dialog prompt to select files. (async () => { return; // Opens a file dialog prompt. // An array of File objects is returned. let files = await FileIO.openDialog({ contentTypes: '.json, text/csv, image/*', // Optional. The accepted file types allowMultiple: true, // Optional. Allows multiple file selection. Default is false }); // ... Do something with the selected files files.forEach((file, index) => { console.log(`File #${index + 1}: ${file.name}`); });})();</script> <script>// Read file contents. (async () => { return; // By default, file data is read as text. // To read a file as a Uint8Array, // set 'readAsTypedArray' to true let contents = await FileIO.read({ data: file, // File/Blob encoding: 'ISO-8859-1', // Optional. If reading as text, set the encoding. Default is UTF-8 readAsTypedArray: false, // Optional. Specifies to read the file as a Uint8Array. Default is false onProgressChange: (progressEvent) => { // Optional. Fires periodically as the file is read let percentLoaded = Number(((progressEvent.loaded / progressEvent.total) * 100).toFixed(2)); console.log(`Percent Loaded: ${percentLoaded}`); } }); // ... Do something with the file contents console.log(contents);})();</script> <script>// Save data to a file. (() => { return; let text = 'My Programming Notes is awesome!'; let filename = 'myProgrammingNotes.txt' // The data to be saved can be a String/Blob/File/Uint8Array let data = text; // Example demonstrating the other datatypes that can be saved //data = new Blob([text], {type: "text/plain;charset=utf-8"}); //data = new File([text], filename, {type: "text/plain;charset=utf-8"}); //data = FileIO.stringToTypedArray(text); // Save the data to a file FileIO.save({ data: data, // String/Blob/File/Uint8Array filename: filename, // Optional if data is a File object decodeBase64Data: false, // Optional. If data is a base64 string, specifies if it should be decoded before saving. Default is false. }); // ... The file is saved to the client})();</script> <script>// Read a remote file (async () => { return; // Remote file url let url = 'https://www.w3.org/TR/PNG/iso_8859-1.txt'; // Other example files //url = 'http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv'; //url = 'http://dummy.restapiexample.com/api/v1/employees'; //url = 'file:///C:/Users/Jr/Desktop/html%20projects/fileIOExample.html'; // Fetch the URL let response = await fetch(url); // Get the response file data let blob = await response.blob(); // Read the remote file as text let contents = await FileIO.read({ data: blob }); // ... Do something with the file contents console.log(contents);})();</script> <script>// Save a remote file (async () => { return; // Remote file url let url = 'https://www.nba.com/lakers/sites/lakers/files/lakers_logo_500.png'; // Other example files //url = 'https://www.w3.org/TR/PNG/iso_8859-1.txt'; //url = 'http://www.africau.edu/images/default/sample.pdf'; //url = 'https://gahp.net/wp-content/uploads/2017/09/sample.pdf' //url = 'http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv'; //url = 'https://file-examples-com.github.io/uploads/2017/02/file-sample_1MB.docx'; // Fetch the URL let response = await fetch(url); // Get the response file data let blob = await response.blob(); // Save the remote file to the client FileIO.save({ data: blob, filename: FileIO.getFilename(url) }); // ... The file is saved to the client})();</script> <script>document.addEventListener("DOMContentLoaded", function(eventLoaded) { // Open file document.querySelector('#btnOpenFile').addEventListener('click', async (e) => { // Open a file dialog prompt to select a file let files = await FileIO.openDialog({ contentTypes: '.txt, .json, text/plain, text/csv, image/*, video/*', allowMultiple: true, }); // Go through each file and read them for (let index = 0; index < files.length; ++index) { let file = files[index]; console.log(`Reading File: ${file.name}`, `, Type: ${file.type}`); // Read the file as a Uint8Array let contents = await FileIO.read({ data: file, readAsTypedArray: true, onProgressChange: (progressEvent) => { let percentLoaded = Number(((progressEvent.loaded / progressEvent.total) * 100).toFixed(2)); updateProgress(file, percentLoaded); } }); console.log(`Finished Reading File: ${file.name}`, `, Type: ${file.type}`); // Show the file showFile(file, contents); } // Hide the status info after a certain amount of time setTimeout(() => updateProgress(null, 0), 5000); }); // Save file document.querySelector('#btnSaveText').addEventListener('click', (e) => { let data = getTextContainer().innerHTML; let filename = 'FileIO_OutputExample.txt'; // Make sure there is data to save if (data.trim().length < 1) { alert('Please load a text file before saving output!'); return; } // Save the text that is in the output div to a file FileIO.save({ data: data, filename: filename, }); });}); let showFile = (file, data) => { if (isImage(file)) { showImage(file, data); } else if (isVideo(file)) { showVideo(file, data); } else { showText(file, data); }} let showImage = (file, data) => { let output = getImageContainer(); let url = 'data:image/png;base64,' + FileIO.typedArrayToBase64(data); // You could also do this below to create a virtual url //let blob = FileIO.convertToBlob(data); //let url = URL.createObjectURL(blob); let divElementContainer = createElementContainerDiv(); let img = document.createElement("img"); img.src = url; img.height = 150; img.title = file.name; divElementContainer.appendChild(img); divElementContainer.appendChild(createFilenameDiv(file)); output.appendChild(divElementContainer);} let showText = (file, data) => { let output = getTextContainer(); let content = ''; try { content = new TextDecoder('UTF-8').decode(data); } catch (e) { content = FileIO.typedArrayToString(data); } let currentText = output.innerHTML; let newText = ''; newText += ` <div style='text-align: center; margin-bottom: 20px;'> File Name: <span style='font-style: italic; text-decoration: underline;'> ${file.name} </span> </div>`; newText += content; if (currentText.length > 0) { newText += '<br />=========================================<br />'; } newText += currentText; output.innerHTML = newText;} let showVideo = (file, data) => { let output = getVideoContainer(); let blob = FileIO.convertToBlob(data); let divElementContainer = createElementContainerDiv(); let video = document.createElement('video'); video.width = 400; video.controls = true; divElementContainer.appendChild(video); let source = document.createElement('source'); source.src = URL.createObjectURL(blob); source.type = file.type; video.appendChild(source); divElementContainer.appendChild(createFilenameDiv(file)); output.appendChild(divElementContainer);} let isImage = (file) => { try { return isType(file, 'image.*'); } catch (e) { let ext = FileIO.getExtension(file.name); return ['jpg', 'gif', 'bmp', 'png'].indexOf(ext) > -1; }} let isVideo = (file) => { try { return isType(file, 'video.*'); } catch (e) { let ext = FileIO.getExtension(file.name); return ['m4v', 'avi','mpg','mp4', 'webm'].indexOf(ext) > -1; }} let isType = (file, typeCheck) => { return file.type.match(typeCheck) != null;} let getImageContainer = () => { return document.querySelector('.imageContainer');} let getTextContainer = () => { return document.querySelector('.textContainer');} let getVideoContainer = () => { return document.querySelector('.videoContainer');} let getFileStatusContainer = () => { return document.querySelector('.fileStatus');} let createElementContainerDiv = () => { let divElementContainer = document.createElement("div"); divElementContainer.style.display = 'inline-block'; divElementContainer.style.textAlign = 'center'; divElementContainer.style.margin = '10px'; return divElementContainer;} let createFilenameDiv = (file) => { let divFileName = document.createElement("div"); divFileName.innerHTML = `${file.name}`; //divFileName.style.fontSize = '12.5px'; divFileName.style.width = '150px'; divFileName.style.margin = 'auto'; divFileName.style.wordWrap = 'break-word'; return divFileName;} let updateProgress = (file, percentLoaded) => { let output = getFileStatusContainer(); if (file) { let status = `File: ${file.name} <br />Percent Loaded: ${percentLoaded}`; output.style.display = 'block'; output.innerHTML = status; console.log(status.replace('<br />', '\n')); } else { output.style.display = null; }}</script></body></html><!-- // http://programmingnotes.org/ -->
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.