upload.ts 1.7 KB

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