uploadDashboardDirective.ts 2.0 KB

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