فهرست منبع

@uppy/utils: improve support of data URI in `dataURItoBlob` (#3080)

Antoine du Hamel 3 سال پیش
والد
کامیت
0cccb686fd
1فایلهای تغییر یافته به همراه16 افزوده شده و 20 حذف شده
  1. 16 20
      packages/@uppy/utils/src/dataURItoBlob.js

+ 16 - 20
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]
-
-  // 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))
-  }
+  const mimeType = opts.mimeType ?? dataURIData?.[1] ?? 'plain/text'
 
-  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 })
 }