next-api-decorators icon indicating copy to clipboard operation
next-api-decorators copied to clipboard

[docs] examples/with-multer

Open leeuwis opened this issue 3 years ago • 3 comments

Using the new middleware decorators

leeuwis avatar May 20 '21 06:05 leeuwis

Hi

just for future reference


import {
  Body,
  createHandler,
  HttpCode,
  Post,
  UploadedFiles,
  UseMiddleware,
} from "@storyofams/next-api-decorators"
import multer from "multer"

const upload = multer({
  dest: "uploads/",
  limits: {
    fileSize: 52428800,
  },
}).array("files")

class DocumentsHandler {
  @Post()
  @HttpCode(201)
  @UseMiddleware(upload)
  public async create(@Body() body, @UploadedFiles() files: any) {
    console.log(body.test)
    console.log(files)
    return {}
  }
}

export default createHandler(DocumentsHandler)

export const config = {
  api: {
    bodyParser: false, // Disallow body parsing, consume as stream
  },
}

and your form

<form action="/api/documents" enctype="multipart/form-data" method="post">

    <input type="file"name="files">
    <input type="text"  name="test">
    <input type="submit">            

</form>

crivera avatar Apr 22 '22 14:04 crivera

Take into consideration that the bodyParser: false will affect any other endpoint that you could add later in this handler (I'm dealing with this right now)

galmatn avatar May 30 '22 13:05 galmatn