FileUtils.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. Copyright (C) 2020 Cloudbase Solutions SRL
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. import JSZip from 'jszip'
  15. export type FileContent = {
  16. name: string,
  17. content: string,
  18. }
  19. class FileUtils {
  20. static async readFile(file: File): Promise<FileContent> {
  21. const reader = new FileReader()
  22. return new Promise((resolve, reject) => {
  23. reader.onload = e => {
  24. const content: any = e.target?.result
  25. resolve({ name: file.name, content })
  26. }
  27. reader.onerror = e => { reject(e) }
  28. reader.readAsText(file)
  29. })
  30. }
  31. static async readContentFromFileList(fileList: FileList | null): Promise<FileContent[]> {
  32. if (!fileList || !fileList.length) {
  33. return []
  34. }
  35. const result: FileContent[] = []
  36. await Promise.all(Array.from(fileList).map(async file => {
  37. if (file.name.substr(file.name.length - 4) === '.zip') {
  38. const zip = await JSZip.loadAsync(file)
  39. await Promise.all(Object.keys(zip.files).map(async zipFileName => {
  40. if (zipFileName.indexOf('__MACOSX') === 0) {
  41. return
  42. }
  43. const zipContent = await zip.files[zipFileName].async('string')
  44. result.push({ name: zipFileName, content: zipContent })
  45. }))
  46. } else {
  47. const fileContent = await this.readFile(file)
  48. result.push(fileContent)
  49. }
  50. }))
  51. return result
  52. }
  53. static readTextFromFirstFile(fileList: FileList): Promise<string | null> {
  54. if (!fileList.length) {
  55. return Promise.resolve(null)
  56. }
  57. const file = fileList[0]
  58. const reader = new FileReader()
  59. return new Promise((resolve, reject) => {
  60. reader.onload = e => {
  61. const content: any = e.target?.result
  62. resolve(content)
  63. }
  64. reader.onerror = e => { reject(e) }
  65. reader.readAsText(file)
  66. })
  67. }
  68. }
  69. export default FileUtils