https://github.com/wobsoriano/h3-formidable
File upload parsing utility for h3 and Nuxt.
https://github.com/wobsoriano/h3-formidable
form h3 multipart nuxt upload
Last synced: 6 months ago
JSON representation
File upload parsing utility for h3 and Nuxt.
- Host: GitHub
- URL: https://github.com/wobsoriano/h3-formidable
- Owner: wobsoriano
- License: mit
- Created: 2022-11-02T05:17:40.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2023-09-28T21:56:49.000Z (about 2 years ago)
- Last Synced: 2025-03-10T13:44:40.440Z (7 months ago)
- Topics: form, h3, multipart, nuxt, upload
- Language: TypeScript
- Homepage:
- Size: 130 KB
- Stars: 62
- Watchers: 3
- Forks: 3
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# h3-formidable
[](https://www.npmjs.com/package/h3-formidable) 
File upload parsing utility for h3 and Nuxt using [formidable](https://github.com/node-formidable/formidable).
Demo - https://stackblitz.com/edit/nuxt-starter-ykuwmn
## Install
```bash
npm install h3-formidable
```## Usage
This example shows Nuxt usage but you can use it with any h3 app.
1. Create a server middleware
```ts
import { createFileParserMiddleware } from 'h3-formidable'export default createFileParserMiddleware({
// formidable options
})
```2. Access files in your api route
```ts
export default eventHandler(async (event) => {
const { files } = event.context.formidable
})
```or you can ditch server middleware and parse files per api route...
```ts
import { readFiles } from 'h3-formidable'export default eventHandler(async (event) => {
const { fields, files, form } = await readFiles(event, {
// formidable options
// https://github.com/node-formidable/formidable#options
})
})
```## Plugins
If you have a custom [plugin](https://github.com/node-formidable/formidable#useplugin-plugin), you can use the `getForm` option to access the incoming form and do whatever you want with it.
```ts
export default eventHandler(async (event) => {
const { fields, files } = await readFiles(event, {
getForm(form) {
form.use(() => {
console.log('woohoo, custom plugin')
})
}
})
})
```Anything inside the getForm callback will be executed before the form is parsed.
## Helpers
```ts
import { firstValues, readBooleans } from 'h3-formidable/helpers'export default eventHandler(async (event) => {
const { fields, files, form } = await readFiles(event)// Gets first values of fields
const exceptions = ['thisshouldbeanarray']
const fieldsSingle = firstValues(form, fields, exceptions)// Converts html form input type="checkbox" "on" to boolean
const expectedBooleans = ['checkbox1', 'wantsNewsLetter', 'hasACar']
const fieldsWithBooleans = readBooleans(fieldsSingle, expectedBooleans)
})
```## TypeScript Shim
```ts
declare module 'h3' {
import type { Result } from 'h3-formidable'interface H3EventContext {
formidable: Result
}
}
```## License
MIT