Save Multi-part form File from request




    The code imports the multer middleware, sets up the storage and limits, and then sets up the upload filter. Then it calls the upload() function.

    The multer middleware lets us pass in the files with data as well. First, it sets up the headers and requests the file from the client. It then ensures that the file paths are consistent with the current directory available. If not, it will create a new file.

    Next, it sets up the middleware. The middleware accepts the pathname of the file as the only argument. It then decides whether to allow the file. If it is allowed, it calls the callback() function. If the file is not allowed, it returns false.

    Library: react

      * Multer middleware let's us pass the files with data as well
      * 1. Header/Request setup:
      * -- usual "application/json" wouldn't work here
      * -- instead use "multipart/form-data" (form-data for postman)
      * 2. Middleware setup:
      * -- Ensure that the file paths are consistent with the current directories available otherwise create new
      * -- limits and filters can be setup
      * 3. Usage
      * -- it must be used as a middleware with the type of incoming data (single/array/fields etc) 
      * -- fieldname argument (`upload.single(fieldname)`) must match with the requested file-name (thru postman form field or from client form input name) 
      * @Resource:
    const upload = multer({
      // setup storage params (destination/filename)
      storage: multer.diskStorage({
        destination(req, file, callback) {
          callback(null, `src/v2/uploads/users`)
        filename(req, file, callback) {
          const AuthName = req?.authenticatedUser?.username;
          const AuthCId = req?.authenticatedUser?.companyId.toString();
          const AuthType = req?.authenticatedUser?.userType;
          const pathName = `${AuthType}_${AuthName}-${AuthCId}`
          callback(null, `${}---${pathName}${path.extname(file.originalname)}`)
      // setup limits (fileSize, fileNameLength etc.)
      limits: {
        fileSize: 1024 * 1024 * 15 // Bytes -> KBs -> MBs
      // decide allowed file types
      fileFilter(req, file, callback) {
        if (["image/png", "image/jpeg"].includes(file.mimetype)) callback(null, true)
        else callback(null, false)
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.