智慧水务管理系统 - 精河县供水工程综合管理平台

fromDataURI.js 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. const DATA_URL_PATTERN = /^([^,;]+\/[^,;]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/;
  8. /**
  9. * Parse data uri to a Buffer or Blob
  10. *
  11. * @param {String} uri
  12. * @param {?Boolean} asBlob
  13. * @param {?Object} options
  14. * @param {?Function} options.Blob
  15. *
  16. * @returns {Buffer|Blob}
  17. */
  18. export default function fromDataURI(uri, asBlob, options) {
  19. const _Blob = (options && options.Blob) || platform.classes.Blob;
  20. const protocol = parseProtocol(uri);
  21. if (asBlob === undefined && _Blob) {
  22. asBlob = true;
  23. }
  24. if (protocol === 'data') {
  25. uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
  26. const match = DATA_URL_PATTERN.exec(uri);
  27. if (!match) {
  28. throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
  29. }
  30. const type = match[1];
  31. const params = match[2];
  32. const encoding = match[3] ? 'base64' : 'utf8';
  33. const body = match[4];
  34. // RFC 2397 section 3: default mediatype is text/plain;charset=US-ASCII
  35. // Bare `data:,` leaves mime undefined; Blob normalises that to "" per spec.
  36. let mime;
  37. if (type) {
  38. mime = params ? type + params : type;
  39. } else if (params) {
  40. mime = 'text/plain' + params;
  41. }
  42. const buffer = Buffer.from(decodeURIComponent(body), encoding);
  43. if (asBlob) {
  44. if (!_Blob) {
  45. throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);
  46. }
  47. return new _Blob([buffer], { type: mime });
  48. }
  49. return buffer;
  50. }
  51. throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
  52. }