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.

30 lines
862 B

  1. import File from './utilities/File'
  2. import Blob from './utilities/Blob'
  3. type DataUriToBlob = (dataUri: string, name?: string) => Blob
  4. const DATA_URI_PREFIX = 'data:'
  5. const DATA_TYPE_DELIMITER = ';'
  6. const DATA_START = ','
  7. const dataUriToBlob: DataUriToBlob = (dataUri, name?) => {
  8. if ((typeof dataUri as unknown) !== 'string') {
  9. throw TypeError('Argument should be a string.')
  10. }
  11. const [encoding, base64] = dataUri.slice(DATA_URI_PREFIX.length).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