diff --git a/shared/utils/files.test.ts b/shared/utils/files.test.ts
index 0bec54a907..1b480eddd4 100644
--- a/shared/utils/files.test.ts
+++ b/shared/utils/files.test.ts
@@ -1,4 +1,9 @@
-import { bytesToHumanReadable, getFileNameFromUrl } from "./files";
+import {
+ bytesToHumanReadable,
+ dataUrlToBlob,
+ dataUrlToFile,
+ getFileNameFromUrl,
+} from "./files";
// Mock the browser detection with a mutable value
let mockIsMacValue = false;
@@ -101,3 +106,69 @@ describe("getFileNameFromUrl", () => {
);
});
});
+
+describe("dataUrlToBlob", () => {
+ it.each(["data:image/png;base64,AP/+", "data:image/png;base64,AP%2F%2B"])(
+ "decodes base64 binary data: %s",
+ async (url) => {
+ const blob = dataUrlToBlob(url);
+ expect(blob.type).toBe("image/png");
+ expect(await readBlobBytes(blob)).toEqual([0, 255, 254]);
+ }
+ );
+
+ it("decodes an empty payload", async () => {
+ expect(
+ await readBlobBytes(dataUrlToBlob("data:image/png;base64,"))
+ ).toEqual([]);
+ });
+
+ it.each([
+ "data:image/svg+xml,%3Csvg%3E%3Ctext%3EHello%2C%20%E4%B8%96%E7%95%8C%3C%2Ftext%3E%3C%2Fsvg%3E",
+ "data:image/svg+xml,",
+ ])("decodes SVG data without base64 encoding: %s", async (url) => {
+ const blob = dataUrlToBlob(url);
+ expect(blob.type).toBe("image/svg+xml");
+ expect(await readBlobBytes(blob)).toEqual(
+ Array.from(
+ new TextEncoder().encode("")
+ )
+ );
+ });
+
+ it.each(["https://example.com/image.png", "data:image/png;base64"])(
+ "rejects an invalid data URL: %s",
+ (url) => {
+ expect(() => dataUrlToBlob(url)).toThrow("Invalid data URL");
+ }
+ );
+});
+
+describe("dataUrlToFile", () => {
+ it("preserves the MIME type and content of a non-base64 image", async () => {
+ const url = "data:image/svg+xml,%3Csvg%2F%3E";
+ const file = dataUrlToFile(url, "pasted-image");
+ expect(file.name).toBe("pasted-image");
+ expect(file.type).toBe("image/svg+xml");
+ expect(await readBlobBytes(file)).toEqual([60, 115, 118, 103, 47, 62]);
+ });
+});
+
+async function readBlobBytes(blob: Blob): Promise {
+ if (typeof FileReader === "undefined") {
+ return Array.from(new Uint8Array(await blob.arrayBuffer()));
+ }
+
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => {
+ if (reader.result instanceof ArrayBuffer) {
+ resolve(Array.from(new Uint8Array(reader.result)));
+ } else {
+ reject(new Error("Expected an ArrayBuffer"));
+ }
+ };
+ reader.onerror = () => reject(reader.error);
+ reader.readAsArrayBuffer(blob);
+ });
+}
diff --git a/shared/utils/files.ts b/shared/utils/files.ts
index f358628e36..cb47b77d4a 100644
--- a/shared/utils/files.ts
+++ b/shared/utils/files.ts
@@ -1,5 +1,5 @@
import { isMac } from "./browser";
-import { isBase64Url, isUrl } from "./urls";
+import { isUrl } from "./urls";
/**
* Converts bytes to human readable string for display
@@ -151,37 +151,39 @@ export function getFileNameFromUrl(url: string) {
}
/**
- * Convert a data URL to a Blob
+ * Converts a base64 or percent-encoded data URL to a Blob.
*
- * @param dataURL The data URL to convert
- * @returns The Blob
+ * @param dataURL the data URL to convert.
+ * @returns the decoded Blob.
+ * @throws Error if the data URL is invalid.
*/
export const dataUrlToBlob = (dataURL: string): Blob => {
- const parts = dataURL.split(",");
- const match = dataURL.match(/:(.*?);/);
- const mime = match ? match[1] : "image/png";
- const blobBin = atob(parts[1]);
- const array = [];
-
- for (let i = 0; i < blobBin.length; i++) {
- array.push(blobBin.charCodeAt(i));
+ const comma = dataURL.indexOf(",");
+ if (!dataURL.startsWith("data:") || comma === -1) {
+ throw new Error("Invalid data URL");
}
- return new Blob([new Uint8Array(array)], {
+ const metadata = dataURL.slice(5, comma);
+ const mime = metadata.split(";")[0] || "image/png";
+ const data = decodeURIComponent(dataURL.slice(comma + 1));
+ const bytes = /;base64$/i.test(metadata)
+ ? Uint8Array.from(atob(data), (char) => char.charCodeAt(0))
+ : new TextEncoder().encode(data);
+
+ return new Blob([bytes], {
type: mime,
});
};
/**
- * Convert a data URL to a File
+ * Converts a data URL to a File.
*
- * @param dataURL The data URL to convert
- * @param filename The filename to use
- * @returns The File
+ * @param dataURL the data URL to convert.
+ * @param filename the filename to use.
+ * @returns the decoded File.
+ * @throws Error if the data URL is invalid.
*/
export const dataUrlToFile = (dataURL: string, filename: string): File => {
- const match = isBase64Url(dataURL);
- const mime = match ? match[1] : "image/png";
const blob = dataUrlToBlob(dataURL);
- return new File([blob], filename, { type: mime });
+ return new File([blob], filename, { type: blob.type });
};