FileUtils.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /**
  2. * File utils is used to read and write files.
  3. *
  4. * Can be used alongside with object serialization to store and load objects from file.
  5. *
  6. * @class
  7. * @static
  8. */
  9. function FileUtils(){}
  10. /**
  11. * Read a local or remote file as text data.
  12. *
  13. * @param {string} fname Path or URL of the file being read.
  14. * @param {Function} onLoad onLoad callback receives the read data as parameter.
  15. * @param {Function} onError onError call is called when a error occurs while reading the file.
  16. */
  17. FileUtils.read = function(fname, onLoad, onError)
  18. {
  19. var file = new XMLHttpRequest();
  20. file.overrideMimeType("text/plain");
  21. file.open("GET", fname, true);
  22. if(onLoad !== undefined)
  23. {
  24. file.onload = function()
  25. {
  26. onLoad(file.response);
  27. };
  28. }
  29. if(onError !== undefined)
  30. {
  31. file.onerror = onError;
  32. }
  33. file.send(null);
  34. };
  35. /**
  36. * Write text to a file and automatically download it from blob storage.
  37. *
  38. * @method writeFile
  39. * @param {string} fname Path of the file to write.
  40. * @param {string} data Text data to be written to the file.
  41. */
  42. FileUtils.write = function(fname, data)
  43. {
  44. var blob = new Blob([data], {type:"octet/stream"});
  45. var download = document.createElement("a");
  46. download.download = fname;
  47. download.href = window.URL.createObjectURL(blob);
  48. download.style.display = "none";
  49. download.onclick = function()
  50. {
  51. document.body.removeChild(this);
  52. };
  53. document.body.appendChild(download);
  54. download.click();
  55. };
  56. /**
  57. * Open file chooser dialog window for the user to select files stored in the system.
  58. *
  59. * The files selected are retrieved using the onLoad callback that receives a array of File objects.
  60. *
  61. * @param {Function} onLoad onLoad callback that receives array of files as parameter.
  62. * @param {string} filter File type filter (e.g. ".zip,.rar, etc)
  63. */
  64. FileUtils.select = function(onLoad, filter)
  65. {
  66. var chooser = document.createElement("input");
  67. chooser.type = "file";
  68. chooser.style.display = "none";
  69. document.body.appendChild(chooser);
  70. if(filter !== undefined)
  71. {
  72. chooser.accept = filter;
  73. }
  74. chooser.onchange = function(event)
  75. {
  76. if(onLoad !== undefined)
  77. {
  78. onLoad(chooser.files);
  79. }
  80. document.body.removeChild(chooser);
  81. };
  82. chooser.click();
  83. };
  84. export {FileUtils};