Skip to content

Commit

Permalink
feat: new function - base64ToFile
Browse files Browse the repository at this point in the history
  • Loading branch information
GreatAuk committed Dec 26, 2023
1 parent 3acb73f commit 51a6a38
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions packages/core/src/base64ToFile.test.ts
Original file line number Diff line number Diff line change
@@ -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')
})
})
19 changes: 19 additions & 0 deletions packages/core/src/base64ToFile.ts
Original file line number Diff line number Diff line change
@@ -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 })
}

0 comments on commit 51a6a38

Please sign in to comment.