feat(transcode): stream uploads and transcode output to prevent memory crashes on large files

This commit is contained in:
yiling
2026-07-29 21:22:49 +08:00
parent 7949c1572a
commit 9a4f8d67c3
5 changed files with 41 additions and 21 deletions
+4 -1
View File
@@ -94,11 +94,14 @@ describe('S3 API', () => {
const res = await app.request('/files/b1/test.webp', {
method: 'PUT',
headers: {
'content-length': body.byteLength.toString(),
},
body,
})
expect(res.status).toBe(200)
expect(await res.text()).toBe('OK')
expect(mockPut).toHaveBeenCalledWith('b1', 'test.webp', expect.any(Buffer), body.byteLength)
expect(mockPut).toHaveBeenCalledWith('b1', 'test.webp', expect.anything(), body.byteLength)
})
})
+3 -2
View File
@@ -18,10 +18,11 @@ const route = new Hono()
.put('/:bucket/:key{.+}', async (c) => {
const bucket = c.req.param('bucket')
const key = c.req.param('key')
const body = await c.req.arrayBuffer()
const contentLength = parseInt(c.req.header('content-length') || '0', 10)
try {
await s3Service.putObject(bucket, key, Buffer.from(body), body.byteLength)
const body = c.req.raw.body ?? (await c.req.arrayBuffer())
await s3Service.putObject(bucket, key, body, contentLength)
return c.text('OK')
} catch (e: unknown) {
const error = e as Error
+6 -9
View File
@@ -26,9 +26,8 @@ export const localUploadRoute = new Hono().put(
}
const contentType = c.req.header('Content-Type')
let buffer: Buffer
let size: number
let finalContentType = contentType
const contentLength = parseInt(c.req.header('Content-Length') || '0', 10)
if (contentType?.includes('multipart/form-data')) {
const body = await c.req.parseBody()
@@ -36,17 +35,15 @@ export const localUploadRoute = new Hono().put(
if (!file) {
return c.text('No file uploaded', 400)
}
buffer = Buffer.from(await file.arrayBuffer())
size = file.size
const buffer = Buffer.from(await file.arrayBuffer())
const size = file.size
finalContentType = file.type || 'application/octet-stream'
await s3Service.putObject(bucket, key, buffer, size, finalContentType)
} else {
const arrayBuffer = await c.req.arrayBuffer()
buffer = Buffer.from(arrayBuffer)
size = arrayBuffer.byteLength
const body = c.req.raw.body ?? (await c.req.arrayBuffer())
await s3Service.putObject(bucket, key, body, contentLength, finalContentType)
}
await s3Service.putObject(bucket, key, buffer, size, finalContentType)
return c.json({ success: true })
},
)