mirror of
https://github.com/transloadit/uppy.git
synced 2026-01-23 02:25:07 +00:00
@uppy/utils: improve support of data URI in dataURItoBlob (#3080)
This commit is contained in:
parent
6cd5309544
commit
0cccb686fd
1 changed files with 16 additions and 20 deletions
|
|
@ -1,32 +1,28 @@
|
|||
const DATA_URL_PATTERN = /^data:([^/]+\/[^,;]+(?:[^,]*?))(;base64)?,([\s\S]*)$/
|
||||
|
||||
module.exports = function dataURItoBlob (dataURI, opts, toFile) {
|
||||
// get the base64 data
|
||||
const data = dataURI.split(',')[1]
|
||||
const dataURIData = DATA_URL_PATTERN.exec(dataURI)
|
||||
|
||||
// user may provide mime type, if not get it from data URI
|
||||
let mimeType = opts.mimeType || dataURI.split(',')[0].split(':')[1].split(';')[0]
|
||||
const mimeType = opts.mimeType ?? dataURIData?.[1] ?? 'plain/text'
|
||||
|
||||
// default to plain/text if data URI has no mimeType
|
||||
if (mimeType == null) {
|
||||
mimeType = 'plain/text'
|
||||
}
|
||||
|
||||
const binary = atob(data)
|
||||
const array = []
|
||||
for (let i = 0; i < binary.length; i++) {
|
||||
array.push(binary.charCodeAt(i))
|
||||
}
|
||||
|
||||
let bytes
|
||||
try {
|
||||
bytes = new Uint8Array(array)
|
||||
} catch (err) {
|
||||
return null
|
||||
let data
|
||||
if (dataURIData[2] != null) {
|
||||
const binary = atob(decodeURIComponent(dataURIData[3]))
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
for (let i = 0; i < binary.length; i++) {
|
||||
bytes[i] = binary.charCodeAt(i)
|
||||
}
|
||||
data = [bytes]
|
||||
} else {
|
||||
data = [decodeURIComponent(dataURIData[3])]
|
||||
}
|
||||
|
||||
// Convert to a File?
|
||||
if (toFile) {
|
||||
return new File([bytes], opts.name || '', { type: mimeType })
|
||||
return new File(data, opts.name || '', { type: mimeType })
|
||||
}
|
||||
|
||||
return new Blob([bytes], { type: mimeType })
|
||||
return new Blob(data, { type: mimeType })
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue