From 0cccb686fdbeba2de39b1d8eb524db4dbccca3a7 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Fri, 6 Aug 2021 12:08:32 +0200 Subject: [PATCH] @uppy/utils: improve support of data URI in `dataURItoBlob` (#3080) --- packages/@uppy/utils/src/dataURItoBlob.js | 36 ++++++++++------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/packages/@uppy/utils/src/dataURItoBlob.js b/packages/@uppy/utils/src/dataURItoBlob.js index 607433811..46ccfdc53 100644 --- a/packages/@uppy/utils/src/dataURItoBlob.js +++ b/packages/@uppy/utils/src/dataURItoBlob.js @@ -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 }) }