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