upload.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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', ['Import failed', 'JSON -> JS Serialization failed: ' + err.message]);
  29. return;
  30. }
  31. scope.$apply(function() {
  32. scope.onUpload({dash: dash});
  33. });
  34. };
  35. };
  36. for (var i = 0, f; f = files[i]; i++) {
  37. var reader = new FileReader();
  38. reader.onload = readerOnload();
  39. reader.readAsText(f);
  40. }
  41. }
  42. var wnd: any = window;
  43. // Check for the various File API support.
  44. if (wnd.File && wnd.FileReader && wnd.FileList && wnd.Blob) {
  45. // Something
  46. document.getElementById('dashupload').addEventListener('change', file_selected, false);
  47. } else {
  48. alertSrv.set('Oops','Sorry, the HTML5 File APIs are not fully supported in this browser.','error');
  49. }
  50. }
  51. };
  52. }
  53. coreModule.directive('dashUpload', uploadDashboardDirective);