fromDataURI.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict';
  2. import AxiosError from '../core/AxiosError.js';
  3. import parseProtocol from './parseProtocol.js';
  4. import platform from '../platform/index.js';
  5. // RFC 2397: data:[<mediatype>][;base64],<data>
  6. // mediatype = type/subtype followed by optional ;name=value parameters
  7. // The `i` flag makes the `;base64` token case-insensitive, matching the WHATWG
  8. // URL/Fetch data URL processor (and therefore the fetch adapter and browsers).
  9. // The remaining character classes do not depend on letter case.
  10. const DATA_URL_PATTERN = /^([^,;/]+\/[^,;/]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/i;
  11. /**
  12. * Parse data uri to a Buffer or Blob
  13. *
  14. * @param {String} uri
  15. * @param {?Boolean} asBlob
  16. * @param {?Object} options
  17. * @param {?Function} options.Blob
  18. *
  19. * @returns {Buffer|Blob}
  20. */
  21. export default function fromDataURI(uri, asBlob, options) {
  22. const _Blob = (options && options.Blob) || platform.classes.Blob;
  23. const protocol = parseProtocol(uri);
  24. if (asBlob === undefined && _Blob) {
  25. asBlob = true;
  26. }
  27. if (protocol === 'data') {
  28. uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
  29. const match = DATA_URL_PATTERN.exec(uri);
  30. if (!match) {
  31. throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
  32. }
  33. const type = match[1];
  34. const params = match[2];
  35. const encoding = match[3] ? 'base64' : 'utf8';
  36. const body = match[4];
  37. // RFC 2397 section 3: default mediatype is text/plain;charset=US-ASCII
  38. // Bare `data:,` leaves mime undefined; Blob normalises that to "" per spec.
  39. let mime = '';
  40. if (type) {
  41. mime = params ? type + params : type;
  42. } else if (params) {
  43. mime = 'text/plain' + params;
  44. }
  45. const buffer =
  46. encoding === 'base64'
  47. ? Buffer.from(
  48. body.replace(/%([\da-f]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16))),
  49. 'base64'
  50. )
  51. : Buffer.from(decodeURIComponent(body), encoding);
  52. if (asBlob) {
  53. if (!_Blob) {
  54. throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);
  55. }
  56. return new _Blob([buffer], { type: mime });
  57. }
  58. return buffer;
  59. }
  60. throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
  61. }