UNPKG

812 BJavaScriptView Raw
1module.exports = function dataURItoBlob (dataURI, opts, toFile) {
2 // get the base64 data
3 const data = dataURI.split(',')[1]
4
5 // user may provide mime type, if not get it from data URI
6 let mimeType = opts.mimeType || dataURI.split(',')[0].split(':')[1].split(';')[0]
7
8 // default to plain/text if data URI has no mimeType
9 if (mimeType == null) {
10 mimeType = 'plain/text'
11 }
12
13 const binary = atob(data)
14 const array = []
15 for (let i = 0; i < binary.length; i++) {
16 array.push(binary.charCodeAt(i))
17 }
18
19 let bytes
20 try {
21 bytes = new Uint8Array(array) // eslint-disable-line compat/compat
22 } catch (err) {
23 return null
24 }
25
26 // Convert to a File?
27 if (toFile) {
28 return new File([bytes], opts.name || '', { type: mimeType })
29 }
30
31 return new Blob([bytes], { type: mimeType })
32}