grafana/public/app/features/dashboard/upload.ts

69 lines
1.9 KiB
TypeScript
Raw Normal View History

2017-12-20 05:33:33 -06:00
import coreModule from 'app/core/core_module';
2018-09-05 02:01:51 -05:00
import appEvents from 'app/core/app_events';
import angular from 'angular';
2018-08-26 13:19:23 -05:00
const template = `
<input type="file" id="dashupload" name="dashupload" class="hide" onchange="angular.element(this).scope().file_selected"/>
2017-12-05 05:19:01 -06:00
<label class="btn btn-success" for="dashupload">
<i class="fa fa-upload"></i>
{{btnText}}
</label>
`;
/** @ngInject */
function uploadDashboardDirective(timer, $location) {
return {
2017-12-20 05:33:33 -06:00
restrict: 'E',
template: template,
scope: {
2017-12-20 05:33:33 -06:00
onUpload: '&',
btnText: '@?',
},
link: (scope, elem) => {
scope.btnText = angular.isDefined(scope.btnText) ? scope.btnText : 'Upload .json File';
function file_selected(evt) {
2018-08-26 13:19:23 -05:00
const files = evt.target.files; // FileList object
const readerOnload = () => {
return e => {
let dash;
try {
dash = JSON.parse(e.target.result);
} catch (err) {
console.log(err);
2018-09-05 02:01:51 -05:00
appEvents.emit('alert-error', ['Import failed', 'JSON -> JS Serialization failed: ' + err.message]);
return;
}
scope.$apply(() => {
scope.onUpload({ dash: dash });
});
};
};
let i = 0;
2018-09-05 05:09:16 -05:00
let file = files[i];
while (file) {
2018-08-26 13:19:23 -05:00
const reader = new FileReader();
reader.onload = readerOnload();
2018-09-05 05:09:16 -05:00
reader.readAsText(file);
i += 1;
file = files[i];
}
}
2018-08-26 13:19:23 -05:00
const wnd: any = window;
// Check for the various File API support.
if (wnd.File && wnd.FileReader && wnd.FileList && wnd.Blob) {
// Something
elem[0].addEventListener('change', file_selected, false);
} else {
appEvents.emit('alert-error', ['Oops', 'The HTML5 File APIs are not fully supported in this browser']);
}
2017-12-20 05:33:33 -06:00
},
};
}
2017-12-20 05:33:33 -06:00
coreModule.directive('dashUpload', uploadDashboardDirective);