f292219da5b88ea5871ccf58d0c181210d23b4e393c5dadced0950ccdab20ba3dd5bb237aaa2a2cb95b4587fe40f326add5ccbb929991774b1de0335158885 1.3 KB

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