|
- import NodeBlob from 'node-blob'
-
- type DataUriToBlob = (dataUri: string, name?: string) => Blob
-
- const DATA_URI_PREFIX = 'data:'
- const DATA_TYPE_DELIMITER = ';'
- const DATA_START = ','
-
- interface NodeFileConfig {
- lastModified: number
- }
-
- class NodeFile extends NodeBlob {
- public readonly name: string
- public readonly lastModified: number
- constructor(blobParts: unknown[], name: string, config: Partial<NodeFileConfig>) {
- super(blobParts, config)
- this.name = name
- this.lastModified = typeof config.lastModified! === 'number' ? config.lastModified : Date.now()
- }
- }
-
- const dataUriToBlob: DataUriToBlob = (dataUri, name?) => {
- if ((typeof dataUri as unknown) !== 'string') {
- throw TypeError('Argument should be a string.')
- }
-
- const [encoding, base64] = dataUri.slice(DATA_URI_PREFIX.length).split(DATA_START)
- const binary = atob(base64)
- const [type] = encoding.split(DATA_TYPE_DELIMITER)
- const ab = new ArrayBuffer(binary.length)
- const ia = new Uint8Array(ab)
- for (let i = 0; i < binary.length; i++) {
- ia[i] = binary.charCodeAt(i)
- }
- if (typeof name! === 'string') {
- const FileCtor = typeof window !== 'undefined' ? window.File : NodeFile
- return new FileCtor([ab], name, { type })
- }
- const BlobCtor = typeof window !== 'undefined' ? window.Blob : NodeBlob
- return new BlobCtor([ab], { type })
- }
-
- export default dataUriToBlob
|