file_utils.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. module.exports = {
  19. fileTypeMap: {
  20. csv: 'text/csv',
  21. json: 'application/json'
  22. },
  23. /**
  24. * download text file
  25. * @param data {String}
  26. * @param fileType {String}
  27. * @param fileName {String}
  28. */
  29. downloadTextFile: function (data, fileType, fileName) {
  30. if ($.browser.msie && $.browser.version < 10) {
  31. this.openInfoInNewTab(data);
  32. } else if (typeof safari !== 'undefined') {
  33. this.safariDownload(data, fileType, fileName);
  34. } else {
  35. try {
  36. var blob = new Blob([data], {
  37. type: (this.fileTypeMap[fileType] || 'text/' + fileType) + ';charset=utf-8;'
  38. });
  39. saveAs(blob, fileName);
  40. } catch (e) {
  41. this.openInfoInNewTab(data);
  42. }
  43. }
  44. },
  45. /**
  46. * open content of text file in new window
  47. * @param data {String}
  48. */
  49. openInfoInNewTab: function (data) {
  50. var newWindow = window.open('');
  51. var newDocument = newWindow.document;
  52. newDocument.write(data);
  53. newWindow.focus();
  54. },
  55. /**
  56. * Hack to dowload text data in Safari
  57. * @param data {String}
  58. * @param fileType {String}
  59. * @param fileName {String}
  60. */
  61. safariDownload: function (data, fileType, fileName) {
  62. var file = 'data:attachment/' + fileType + ';charset=utf-8,' + encodeURI(data);
  63. var linkEl = document.createElement("a");
  64. linkEl.href = file;
  65. linkEl.download = fileName;
  66. document.body.appendChild(linkEl);
  67. linkEl.click();
  68. document.body.removeChild(linkEl);
  69. },
  70. fileNameFromPath: function(path) {
  71. return path.split('/').slice(-1);
  72. }
  73. };