upload.ts 1.8 KB

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