Add projects/node/packages/image-upload/src/Files.test.ts
This commit is contained in:
parent
355d8c8e51
commit
b05cdfcfaa
54
packages/image-upload/src/Files.test.ts
Normal file
54
packages/image-upload/src/Files.test.ts
Normal file
@ -0,0 +1,54 @@
|
||||
import * as Files from './Files'
|
||||
|
||||
describe('Files', () => {
|
||||
|
||||
const pngDataURL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUg' +
|
||||
'AAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='
|
||||
|
||||
function base64ToArrayBuffer(base64: string): ArrayBuffer {
|
||||
const bytesString = atob(base64)
|
||||
const arrayBuffer = new ArrayBuffer(bytesString.length)
|
||||
const iArray = new Uint8Array(arrayBuffer)
|
||||
for (let i = 0; i < bytesString.length; i++) {
|
||||
iArray[i] = bytesString.charCodeAt(i)
|
||||
}
|
||||
return arrayBuffer
|
||||
}
|
||||
|
||||
function dataURLToBlob(dataURL: string) {
|
||||
const [type, base64] = dataURL.split(';base64,', 2)
|
||||
const arrayBuffer = base64ToArrayBuffer(base64)
|
||||
|
||||
return new Blob([arrayBuffer], {
|
||||
type: type.replace(/^data:/, ''),
|
||||
})
|
||||
}
|
||||
|
||||
const pngBlob = dataURLToBlob(pngDataURL)
|
||||
|
||||
describe('readAsDataURL', () => {
|
||||
it('asynchronously reads a file and returns a base64 string', async () => {
|
||||
const file = new File([pngBlob], 'test.png', {
|
||||
type: pngBlob.type,
|
||||
})
|
||||
const result = await Files.readAsDataURL(file)
|
||||
expect(result).toEqual(pngDataURL)
|
||||
})
|
||||
})
|
||||
|
||||
describe('readAsArrayBuffer', () => {
|
||||
it('asynchronously reads a file and returns an ArrayBuffer', async () => {
|
||||
const base64 = pngDataURL.split(';base64,', 2)[1]
|
||||
const file = new File([pngBlob], 'test.png', {
|
||||
type: pngBlob.type,
|
||||
})
|
||||
const result = await Files.readAsArrayBuffer(file)
|
||||
expect(result).toEqual(base64ToArrayBuffer(base64))
|
||||
})
|
||||
})
|
||||
|
||||
// describe('readAsArrayBuffer', () => {
|
||||
|
||||
// })
|
||||
|
||||
})
|
||||
@ -4,7 +4,8 @@ function attachErrorListener(
|
||||
file: File,
|
||||
reject: (err: Error) => void,
|
||||
) {
|
||||
reader.onerror = ev => reject(new Error('Error reading file: ' + file.name))
|
||||
reader.onerror = ev => reject(new Error('Error reading file: ' +
|
||||
(reader.error ? reader.error.message : file.name)))
|
||||
}
|
||||
|
||||
export async function readAsDataURL(file: File): Promise<string> {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user