hashing.ts 780 B

123456789101112131415161718192021222324252627
  1. import IpfsHash from 'ipfs-only-hash'
  2. const DEFAULT_CHUNK_SIZE = 128 * 1024 * 1024 // 128 MB
  3. const createIterableFile = (file: File | Blob, chunkSize: number): AsyncIterable<Uint8Array> => {
  4. async function* iterator(): AsyncIterator<Uint8Array> {
  5. let offset = 0
  6. let fileSlice
  7. let result
  8. while (offset < file.size) {
  9. fileSlice = file.slice(offset, chunkSize + offset)
  10. offset += chunkSize
  11. result = await fileSlice.arrayBuffer()
  12. yield new Uint8Array(result)
  13. }
  14. }
  15. return {
  16. [Symbol.asyncIterator]: iterator,
  17. }
  18. }
  19. export const computeFileHash = async (file: File | Blob, chunkSize = DEFAULT_CHUNK_SIZE): Promise<string> => {
  20. const iterableFile = createIterableFile(file, chunkSize)
  21. return await IpfsHash.of(iterableFile)
  22. }