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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// 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!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 |
// ============================================================================ // 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!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 |
<!-- // ============================================================================ // 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.
Leave a Reply