upload.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import coreModule from 'app/core/core_module';
  2. var 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: function(scope) {
  18. function file_selected(evt) {
  19. var files = evt.target.files; // FileList object
  20. var readerOnload = function() {
  21. return function(e) {
  22. var 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(function() {
  31. scope.onUpload({ dash: dash });
  32. });
  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);