upload.ts 1.7 KB

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