file_utils.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. var stringUtils = require('utils/string_utils');
  19. module.exports = {
  20. fileTypeMap: {
  21. csv: 'text/csv',
  22. json: 'application/json'
  23. },
  24. /**
  25. * download text file
  26. * @param data {String}
  27. * @param fileType {String}
  28. * @param fileName {String}
  29. */
  30. downloadTextFile: function (data, fileType, fileName) {
  31. if ($.browser.msie && $.browser.version < 10) {
  32. this.openInfoInNewTab(data);
  33. } else if (typeof safari !== 'undefined') {
  34. this.safariDownload(data, fileType, fileName);
  35. } else {
  36. try {
  37. var blob = new Blob([data], {
  38. type: (this.fileTypeMap[fileType] || 'text/' + fileType) + ';charset=utf-8;'
  39. });
  40. saveAs(blob, fileName);
  41. } catch (e) {
  42. this.openInfoInNewTab(data);
  43. }
  44. }
  45. },
  46. /**
  47. * open content of text file in new window
  48. * @param data {String}
  49. */
  50. openInfoInNewTab: function (data) {
  51. var newWindow = window.open('');
  52. var newDocument = newWindow.document;
  53. newDocument.write(data);
  54. newWindow.focus();
  55. },
  56. /**
  57. * Hack to dowload text data in Safari
  58. * @param data {String}
  59. * @param fileType {String}
  60. * @param fileName {String}
  61. */
  62. safariDownload: function (data, fileType, fileName) {
  63. var file = 'data:attachment/' + fileType + ';charset=utf-8,' + encodeURI(data);
  64. var linkEl = document.createElement("a");
  65. linkEl.href = file;
  66. linkEl.download = fileName;
  67. document.body.appendChild(linkEl);
  68. linkEl.click();
  69. document.body.removeChild(linkEl);
  70. }
  71. };