Upload de arquivo com express usando o multer retornando MulterError: Unexpected field


(Carlos Daniel) #1

Estou criando um sistema para onde trabalho que tem que receber um pdf exportado de outro sistema e converter para Json, porém ao enviar o pdf via método post utilizando o Insomnia ele retorna o seguinte erro:

POST /posts 500 12.013 ms - 1225
MulterError: Unexpected field
    at wrappedFileFilter (/home/xcall/Desktop/uploadProject/backend/node_modules/multer/index.js:40:19)
    at Busboy.<anonymous> (/home/xcall/Desktop/uploadProject/backend/node_modules/multer/lib/make-middleware.js:114:7)
    at Busboy.emit (events.js:315:20)
    at Busboy.emit (/home/xcall/Desktop/uploadProject/backend/node_modules/busboy/lib/main.js:38:33)
    at PartStream.<anonymous> (/home/xcall/Desktop/uploadProject/backend/node_modules/busboy/lib/types/multipart.js:213:13)
    at PartStream.emit (events.js:315:20)
    at HeaderParser.<anonymous> (/home/xcall/Desktop/uploadProject/backend/node_modules/dicer/lib/Dicer.js:51:16)
    at HeaderParser.emit (events.js:315:20)
    at HeaderParser._finish (/home/xcall/Desktop/uploadProject/backend/node_modules/dicer/lib/HeaderParser.js:68:8)
    at SBMH.<anonymous> (/home/xcall/Desktop/uploadProject/backend/node_modules/dicer/lib/HeaderParser.js:40:12)

O meus arquivos contem os seguintes códigos:

index.js:

const express = require('express')
const morgan = require('morgan')
const app = express()
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.use(morgan('dev'))
app.use(require('./routes'))
app.listen(3000)

routes.js:

const routes = require('express').Router()
const multer = require('multer')
const multerConfig = require('./config/multer')

routes.post('/posts', multer(multerConfig).single('file'), (req, res) => {
    console.log(req.file)
    return res.json("posts")
})
module.exports = routes

multer.js:

const multer = require('multer')
const path = require('path')
const crypto = require('crypto')

module.exports = {
    dest: path.resolve(__dirname, '..', '..', 'tmp', 'uploads'),
    storage: multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, path.resolve(__dirname, '..', '..', 'tmp', 'uploads'))
        },
        filename: (req, file, cb) => {
            crypto.randomBytes(16, (err, hash) => {
                if (err) cb(err)

                const filename = `${hash.toString('hex')}-${file.originalname}`

                cb(null, filename)
            })
        }
    }),
    limits: {
        fileSize: 2 * 1024 * 1024
    },
    fileFilter: (req, file, cb) => {
        const allowedMimes = [
            "application/pdf"
        ]

        if (allowedMimes.includes(file.mimeTypes)) {
            cb(null, true)
        } else {
            cb(new Error('Arquivo diferente do esperado.'))
        } 
    }
}

Qualquer ajuda será bem vinda, sou novo em fóruns, agradeço desde já.