|
36 | 36 | }()), |
37 | 37 | BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || |
38 | 38 | window.MozBlobBuilder || window.MSBlobBuilder, |
| 39 | + dataURIPattern = /^data:((.*?)(;charset=.*?)?)(;base64)?,/, |
39 | 40 | dataURLtoBlob = (hasBlobConstructor || BlobBuilder) && window.atob && |
40 | 41 | window.ArrayBuffer && window.Uint8Array && function (dataURI) { |
41 | | - var byteString, |
| 42 | + var matches, |
| 43 | + mediaType, |
| 44 | + isBase64, |
| 45 | + dataString, |
| 46 | + byteString, |
42 | 47 | arrayBuffer, |
43 | 48 | intArray, |
44 | 49 | i, |
45 | | - mimeString, |
46 | 50 | bb; |
47 | | - if (dataURI.split(',')[0].indexOf('base64') >= 0) { |
| 51 | + // Parse the dataURI components as per RFC 2397 |
| 52 | + matches = dataURI.match(dataURIPattern); |
| 53 | + if (!matches) throw new Error('invalid data URI'); |
| 54 | + // Default to text/plain;charset=US-ASCII |
| 55 | + mediaType = matches[2] ? |
| 56 | + matches[1] : |
| 57 | + 'text/plain' + (matches[3] || ';charset=US-ASCII'); |
| 58 | + isBase64 = !!matches[4]; |
| 59 | + dataString = dataURI.slice(matches[0].length); |
| 60 | + if (isBase64) { |
48 | 61 | // Convert base64 to raw binary data held in a string: |
49 | | - byteString = atob(dataURI.split(',')[1]); |
| 62 | + byteString = atob(dataString); |
50 | 63 | } else { |
51 | 64 | // Convert base64/URLEncoded data component to raw binary data: |
52 | | - byteString = decodeURIComponent(dataURI.split(',')[1]); |
| 65 | + byteString = decodeURIComponent(dataString); |
53 | 66 | } |
54 | 67 | // Write the bytes of the string to an ArrayBuffer: |
55 | 68 | arrayBuffer = new ArrayBuffer(byteString.length); |
56 | 69 | intArray = new Uint8Array(arrayBuffer); |
57 | 70 | for (i = 0; i < byteString.length; i += 1) { |
58 | 71 | intArray[i] = byteString.charCodeAt(i); |
59 | 72 | } |
60 | | - // Separate out the mime component: |
61 | | - mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; |
62 | 73 | // Write the ArrayBuffer (or ArrayBufferView) to a blob: |
63 | 74 | if (hasBlobConstructor) { |
64 | 75 | return new Blob( |
65 | 76 | [hasArrayBufferViewSupport ? intArray : arrayBuffer], |
66 | | - {type: mimeString} |
| 77 | + {type: mediaType} |
67 | 78 | ); |
68 | 79 | } |
69 | 80 | bb = new BlobBuilder(); |
70 | 81 | bb.append(arrayBuffer); |
71 | | - return bb.getBlob(mimeString); |
| 82 | + return bb.getBlob(mediaType); |
72 | 83 | }; |
73 | 84 | if (window.HTMLCanvasElement && !CanvasPrototype.toBlob) { |
74 | 85 | if (CanvasPrototype.mozGetAsFile) { |
|
0 commit comments