diff --git a/README.md b/README.md index 27d7069..fd86b61 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,7 @@ pnpm add @utopia-utils/dom * onTimeout: wrap for setTimeout, return a function to remove the timeout。[source](https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/onTimeout.ts) * onWindowFocus: 监听 window focus 和 visibilitychange 事件,当窗口可见时,触发回调。[source](https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/onWindowFocus.ts) * formatNumberThousand: 数字千分位格式化。[source](https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/formatNumberThousand.ts) +* base64ToFile: base64 转 File, 如图片裁剪时,我们获取到的是 base64,但上传接口一般需要 formData 上传。[source](https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/ base64ToFile.ts) ### 类型判断 ```bash diff --git a/packages/core/src/base64ToFile.test.ts b/packages/core/src/base64ToFile.test.ts new file mode 100644 index 0000000..d8bd1de --- /dev/null +++ b/packages/core/src/base64ToFile.test.ts @@ -0,0 +1,17 @@ +/** + * @vitest-environment happy-dom + */ + +import { describe, expect, it } from 'vitest' + +import { base64ToFile } from './base64ToFile' + +describe('base64ToFile', () => { + it('should convert a base64 string to a File object', () => { + const base64 = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxQTEhQUExQWFhQYGBgYGBgYGBgYGBgYGBgYGBgYGBgYHSggGBolGxgXITEhJSkrLi4uGB8zODMsNygtLisB' + const file = base64ToFile(base64, 'test.jpg') + expect(file).toBeInstanceOf(File) + expect(file.name).toBe('test.jpg') + expect(file.type).toBe('image/jpeg') + }) +}) diff --git a/packages/core/src/base64ToFile.ts b/packages/core/src/base64ToFile.ts new file mode 100644 index 0000000..db9e717 --- /dev/null +++ b/packages/core/src/base64ToFile.ts @@ -0,0 +1,19 @@ +/** + * The function converts a base64 string to a File object with the specified filename and optional + * mimeType. + * @param {string} base64 - A string representing the base64 encoded data of the file. + * @param {string} filename - The `filename` parameter is a string that represents the desired name of + * the file that will be created from the base64 data. + * @returns a File object. + */ +export function base64ToFile(base64: string, filename: string): File { + const arr = base64.split(',') + const mime = arr[0].match(/:(.*?);/)![1] + const bstr = atob(arr[1]) + let n = bstr.length + const u8arr = new Uint8Array(n) + while (n--) + u8arr[n] = bstr.charCodeAt(n) + + return new File([u8arr], filename, { type: mime }) +}