( newFiles: File[] )
| 17 | } |
| 18 | |
| 19 | export async function writeFiles( |
| 20 | newFiles: File[] |
| 21 | ): Promise<{ [key: string]: string }> { |
| 22 | console.log('save file to OPFS', newFiles); |
| 23 | if (!newFiles.length) return {}; |
| 24 | |
| 25 | const storageRoot = await getRoot(); |
| 26 | const filenameMapping: { [key: string]: string } = {}; |
| 27 | |
| 28 | if (storageRoot) { |
| 29 | for (const file of newFiles) { |
| 30 | const originalFileName = file.name; |
| 31 | const newSubDir = await storageRoot.getDirectoryHandle('fileuploads', { |
| 32 | create: true, |
| 33 | }); |
| 34 | |
| 35 | let newFileName = file.name; |
| 36 | let fileExists = await checkFileExists(newSubDir, newFileName); |
| 37 | let counter = 1; |
| 38 | |
| 39 | while (fileExists) { |
| 40 | newFileName = addSuffixToFile(file.name, counter); |
| 41 | fileExists = await checkFileExists(newSubDir, newFileName); |
| 42 | counter++; |
| 43 | } |
| 44 | |
| 45 | const newFile = await newSubDir.getFileHandle(newFileName, { |
| 46 | create: true, |
| 47 | }); |
| 48 | |
| 49 | const wtr = await newFile.createWritable(); |
| 50 | try { |
| 51 | await wtr.write(await file.arrayBuffer()); |
| 52 | filenameMapping[originalFileName] = newFileName; // Map the original filename to the new filename |
| 53 | } finally { |
| 54 | await wtr.close(); |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | return filenameMapping; // Return the mapping object |
| 60 | } |
| 61 | |
| 62 | async function checkFileExists( |
| 63 | directoryHandle: FileSystemDirectoryHandle, |
no test coverage detected