uploadDashboardDirective.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import coreModule from 'app/core/core_module';
  2. import appEvents from 'app/core/app_events';
  3. import angular from 'angular';
  4. const template = `
  5. <input type="file" id="dashupload" name="dashupload" class="hide" onchange="angular.element(this).scope().file_selected"/>
  6. <label class="btn btn-primary" for="dashupload">
  7. <i class="fa fa-upload"></i>
  8. {{btnText}}
  9. </label>
  10. `;
  11. /** @ngInject */
  12. export function uploadDashboardDirective(timer, $location) {
  13. return {
  14. restrict: 'E',
  15. template: template,
  16. scope: {
  17. onUpload: '&',
  18. btnText: '@?',
  19. },
  20. link: (scope, elem) => {
  21. scope.btnText = angular.isDefined(scope.btnText) ? scope.btnText : 'Upload .json File';
  22. function file_selected(evt) {
  23. const files = evt.target.files; // FileList object
  24. const readerOnload = () => {
  25. return e => {
  26. let dash;
  27. try {
  28. dash = JSON.parse(e.target.result);
  29. } catch (err) {
  30. console.log(err);
  31. appEvents.emit('alert-error', ['Import failed', 'JSON -> JS Serialization failed: ' + err.message]);
  32. return;
  33. }
  34. scope.$apply(() => {
  35. scope.onUpload({ dash: dash });
  36. });
  37. };
  38. };
  39. let i = 0;
  40. let file = files[i];
  41. while (file) {
  42. const reader = new FileReader();
  43. reader.onload = readerOnload();
  44. reader.readAsText(file);
  45. i += 1;
  46. file = files[i];
  47. }
  48. }
  49. const wnd: any = window;
  50. // Check for the various File API support.
  51. if (wnd.File && wnd.FileReader && wnd.FileList && wnd.Blob) {
  52. // Something
  53. elem[0].addEventListener('change', file_selected, false);
  54. } else {
  55. appEvents.emit('alert-error', ['Oops', 'The HTML5 File APIs are not fully supported in this browser']);
  56. }
  57. },
  58. };
  59. }
  60. coreModule.directive('dashUpload', uploadDashboardDirective);