Skip to content

Commit 88e1c36

Browse files
committed
feat: upload support blob
1 parent 3b6fbf5 commit 88e1c36

File tree

3 files changed

+28
-10
lines changed

3 files changed

+28
-10
lines changed

src/api/upload.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import ky from 'ky'
22
import { request, toResponse } from '../request'
33
import type { Upload } from '../types/api-responses'
4+
import type { Blob as NodeBlob } from 'buffer'
45

56
export const token = <T = Upload.TokenResponse>(md5: string) =>
67
toResponse<T>(
@@ -9,12 +10,15 @@ export const token = <T = Upload.TokenResponse>(md5: string) =>
910
})
1011
)
1112

12-
export const upload = async (image: File | Buffer, token: string) => {
13-
let file: File
13+
export const upload = async (
14+
image: NodeBlob | Blob | Buffer,
15+
token: string
16+
) => {
17+
let file: Blob
1418
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(image)) {
15-
file = new File([image.buffer], '?')
19+
file = new Blob([image.buffer])
1620
} else {
17-
file = image as File
21+
file = image as Blob
1822
}
1923
const formData = new FormData()
2024
formData.append('file', file)

src/node-shim.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { randomUUID } from 'crypto'
22
import {
3+
Blob,
34
File,
45
FormData,
56
Headers,
@@ -20,6 +21,7 @@ if (!globals.fetch) {
2021

2122
if (!globals.FormData) {
2223
globals.File = File
24+
globals.Blob = Blob
2325
globals.FormData = FormData
2426
}
2527

tests/api/upload.test.ts

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { Blob } from 'buffer'
12
import sharp from 'sharp'
23
import Md5 from 'md5'
34
import { describe, expect, it } from 'vitest'
@@ -28,11 +29,22 @@ describe('upload should work', async () => {
2829
token = result.data.uptoken
2930
})
3031

31-
it('upload image', async () => {
32-
const result = await api.upload.upload(image, token)
33-
expect(result.success).toBe(true)
34-
expect(result.fileUrl).to.be.a('string')
35-
expect(result.id).to.be.a('string')
36-
expect(result.key).a('string')
32+
describe('upload image', () => {
33+
it('Buffer should work', async () => {
34+
// @ts-expect-error
35+
const result = await api.upload.upload(new Blob([image.buffer]), token)
36+
expect(result.success).toBe(true)
37+
expect(result.fileUrl).to.be.a('string')
38+
expect(result.id).to.be.a('string')
39+
expect(result.key).a('string')
40+
})
41+
42+
it('Blob should work', async () => {
43+
const result = await api.upload.upload(image, token)
44+
expect(result.success).toBe(true)
45+
expect(result.fileUrl).to.be.a('string')
46+
expect(result.id).to.be.a('string')
47+
expect(result.key).a('string')
48+
})
3749
})
3850
})

0 commit comments

Comments
 (0)