instantcommerce / next-api-decorators

Collection of decorators to create typed Next.js API routes, with easy request validation and transformation.
https://next-api-decorators.vercel.app
MIT License
417 stars 29 forks source link

[docs] examples/with-multer #143

Open leeuwis opened 3 years ago

leeuwis commented 3 years ago

Using the new middleware decorators

crivera commented 2 years ago

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>
galmatn commented 2 years ago

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)

GreccoOliva-Franco commented 1 year ago

@galmatn That's exactly what I'm experiencing right now. Any updates on handling some endpoints with multer and others with bodyParser?