fromDataURI.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use strict';
  2. import AxiosError from '../core/AxiosError.js';
  3. import parseProtocol from './parseProtocol.js';
  4. import platform from '../platform/index.js';
  5. const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
  6. /**
  7. * Parse data uri to a Buffer or Blob
  8. *
  9. * @param {String} uri
  10. * @param {?Boolean} asBlob
  11. * @param {?Object} options
  12. * @param {?Function} options.Blob
  13. *
  14. * @returns {Buffer|Blob}
  15. */
  16. export default function fromDataURI(uri, asBlob, options) {
  17. const _Blob = options && options.Blob || platform.classes.Blob;
  18. const protocol = parseProtocol(uri);
  19. if (asBlob === undefined && _Blob) {
  20. asBlob = true;
  21. }
  22. if (protocol === 'data') {
  23. uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
  24. const match = DATA_URL_PATTERN.exec(uri);
  25. if (!match) {
  26. throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
  27. }
  28. const mime = match[1];
  29. const isBase64 = match[2];
  30. const body = match[3];
  31. const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8');
  32. if (asBlob) {
  33. if (!_Blob) {
  34. throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);
  35. }
  36. return new _Blob([buffer], {type: mime});
  37. }
  38. return buffer;
  39. }
  40. throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
  41. }