SlimRunner

generic-file-reader

Jan 18th, 2021
1,403
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (function() {
  2.     'use strict';
  3.    
  4.     function fileCallback(fileData) {
  5.         console.log(fileData);
  6.     }
  7.    
  8.     let background = document.createElement('div');
  9.     background.style.position = 'fixed';
  10.     background.style.left = '0';
  11.     background.style.top = '0';
  12.     background.style.width = '100%';
  13.     background.style.height = '100%';
  14.     background.style.zIndex = '99';
  15.     background.style.background = 'rgba(0,0,0,0.4)';
  16.     let dialFrame = document.createElement('div');
  17.     dialFrame.style.position = 'absolute';
  18.     dialFrame.style.padding = '12px';
  19.     dialFrame.style.left = '50%';
  20.     dialFrame.style.top = '50%';
  21.     dialFrame.style.transform = 'translate(-50%, -50%)';
  22.     dialFrame.style.background = 'white';
  23.     let promptButton = document.createElement('input');
  24.     promptButton.setAttribute('type', 'file');
  25.     promptButton.setAttribute('accept', '.txt');
  26.     promptButton.style.display = 'block';
  27.     let cancelButton = document.createElement('button');
  28.     cancelButton.setAttribute('type', 'button');
  29.     cancelButton.innerText = 'Cancel';
  30.     cancelButton.style.display = 'block';
  31.    
  32.     document.body.appendChild(background);
  33.     background.appendChild(dialFrame);
  34.     dialFrame.appendChild(promptButton);
  35.     dialFrame.appendChild(cancelButton);
  36.    
  37.     promptButton.addEventListener('change', buttonChange);
  38.     cancelButton.addEventListener('click', cancelClick);
  39.    
  40.     function removeListeners() {
  41.         promptButton.removeEventListener('change', buttonChange);
  42.         cancelButton.removeEventListener('click', cancelClick);
  43.     }
  44.    
  45.     function buttonChange(evt) {
  46.         let fread = new FileReader();
  47.         fread.addEventListener('load', () => {
  48.             // return found value to callback for processing
  49.             fileCallback(fread.result);
  50.         }, {once: true});
  51.        
  52.         // here you can read as something else if needed
  53.         fread.readAsText(evt.target.files[0]);
  54.         console.log('file was read');
  55.         removeListeners();
  56.         background.remove();
  57.     }
  58.    
  59.     function cancelClick(evt) {
  60.         console.log('dialog was canceled');
  61.         removeListeners();
  62.         background.remove();
  63.     }
  64. }());
  65.  
Advertisement
Add Comment
Please, Sign In to add comment