Skip to content

Instantly share code, notes, and snippets.

@linnil1
Created May 5, 2022 11:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save linnil1/1cf310089521d2632ccb745a6e780e0c to your computer and use it in GitHub Desktop.
Save linnil1/1cf310089521d2632ccb745a6e780e0c to your computer and use it in GitHub Desktop.
Handle form data (file) in Nuxt3 h3 server
import {File} from 'fetch-blob/file.js'
import {Blob} from 'buffer'
import {default: Busboy} from 'busboy'
async function readForm(req) {
// My implementation is similar to
// https://github.com/cloudflare/miniflare/blob/master/packages/core/src/standards/http.ts#L302
const data = {}
await new Promise( (resolve) => {
const bb = Busboy({ headers: req.headers })
bb.on('field', (key, value) => {
data[key] = value
})
bb.on('file', (key, file, info) => {
const buffer_array = []
file.on('data', (data) => {
buffer_array.push(Buffer.from(data, {'type': info.mimeType}))
}).on('close', () => {
data[key] = new File(buffer_array, info.filename, {'type': info.mimeType})
})
})
bb.on('close', resolve)
req.pipe(bb)
})
return data
}
export default defineEventHandler( async (event) => {
if (event.req.method == "POST") {
let data = await readForm(event.req)
console.log(data)
// do-something
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment