Useful methods for file-related functions.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

31 lines
875 B

  1. type DataUriToBlob = (dataUri: string, name?: string) => Blob
  2. const DATA_URI_PREFIX = 'data:'
  3. const DATA_TYPE_DELIMITER = ';'
  4. const DATA_START = ','
  5. const dataUriToBlob: DataUriToBlob = (dataUri, name) => {
  6. if (typeof dataUri as unknown !== 'string') {
  7. throw TypeError('Argument should be a string.')
  8. }
  9. const [encoding, base64] = dataUri
  10. .slice(DATA_URI_PREFIX.length)
  11. .split(DATA_START)
  12. const binary = atob(base64)
  13. const [type,] = encoding.split(DATA_TYPE_DELIMITER)
  14. const ab = new ArrayBuffer(binary.length)
  15. const ia = new Uint8Array(ab)
  16. for (let i = 0; i < binary.length; i++) {
  17. ia[i] = binary.charCodeAt(i)
  18. }
  19. if (typeof name! === 'string') {
  20. return new File([ab], name, { type, })
  21. }
  22. return new Blob([ab], { type, })
  23. }
  24. export default dataUriToBlob
  25. // TODO make code portable to Node! Maybe return a buffer instead of blob?