Created
May 5, 2022 11:06
-
-
Save linnil1/1cf310089521d2632ccb745a6e780e0c to your computer and use it in GitHub Desktop.
Handle form data (file) in Nuxt3 h3 server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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