upload.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. ///<reference path="../../headers/common.d.ts" />
  2. import coreModule from 'app/core/core_module';
  3. var template = `
  4. <input type="file" id="dashupload" name="dashupload" class="hide"/>
  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: function(scope) {
  19. function file_selected(evt) {
  20. var files = evt.target.files; // FileList object
  21. var readerOnload = function() {
  22. return function(e) {
  23. var dash;
  24. try {
  25. dash = JSON.parse(e.target.result);
  26. } catch (err) {
  27. console.log(err);
  28. scope.appEvent('alert-error', [
  29. 'Import failed',
  30. 'JSON -> JS Serialization failed: ' + err.message,
  31. ]);
  32. return;
  33. }
  34. scope.$apply(function() {
  35. scope.onUpload({ dash: dash });
  36. });
  37. };
  38. };
  39. for (var i = 0, f; (f = files[i]); i++) {
  40. var reader = new FileReader();
  41. reader.onload = readerOnload();
  42. reader.readAsText(f);
  43. }
  44. }
  45. var 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
  50. .getElementById('dashupload')
  51. .addEventListener('change', file_selected, false);
  52. } else {
  53. alertSrv.set(
  54. 'Oops',
  55. 'Sorry, the HTML5 File APIs are not fully supported in this browser.',
  56. 'error'
  57. );
  58. }
  59. },
  60. };
  61. }
  62. coreModule.directive('dashUpload', uploadDashboardDirective);