Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
Retrieving a request within an express controller to store file

I have a express backend I am currently building. I created a router and controller system that process each and every request that comes through the server. I am currently trying to save image files that are sent with the profile as profile picture. I am currently integrating multer into my backend. I have the multer destination set but I am not sure how to grab the request that passing through in order to actually save the file before the request gets to the controller.

my app.js:

...
// app.use(logger('dev'))
app.use(cors());
app.use(cookieParser())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended : true }));
app.use(session({
  secret: 'helloworld',
  cookie: {maxAge: 60000},
  saveUninitialized: false,
}))
app.use(morgan('dev'))
app.use(fileUpload());

app.use('/api/auth', AuthenticationRouter)
app.use('/api/user', UserRouter)
app.use('/api/profile', ProfileRouter)
app.use('/api/follow', FollowRouter)
app.use('/api/post', PostRouter)
app.use('/api/like', LikeRouter)
app.use('/api/edit', EditRouter)
app.use('/api/download', DownloadRouter)
app.use('/api/comment', CommentRouter)

the following is the routers page. this is the point where i am trying to grab the request and save the file that was sent with the request. I am not sure how to inject and grab the request object at this point routers:

const multer = require('multer')
const upload = multer({dest:'../client/static/images/ProfilePictures'})

const router = require("express").Router()
const profileController = require("../../controllers/UserControllers/ProfileController.js");

router
  .route('/')
  .get(profileController.get)
  .post(upload,single(''), profileController.post)
  .delete(profileController.delete)
  .patch(profileController.patch)

module.exports = router;

controller:

const Profile = require("../../models/UserModels/Profiles.js")
const User = require('../../models/UserModels/Users.js')

const profileController = {
  post:(req, res) => {
    console.log(req.files.profile_pic.name)
    let body = req.body
    let file = req.files.profile_pic
    Profile.create({
      profile_pic: file.name,
      f_name: body.f_name,
      l_name: body.l_name,
      bio: body.bio,
      location: body.location,
      sm_facebook: body.sm_facebook,
      sm_instagram: body.sm_instagram,
      sm_twitter: body.sm_twitter,
      sm_website: body.sm_website,
      followers: body.followers,
      following: body.following,
      photos: body.photos,
      downloads: body.downloads,
      edits: body.edits,
      userId: body.userId
    })
    .then((data) => {
      res.send(data).status(200)
    })
    .catch((err) => {
      console.error(err)
      res.send(err).status(400)
    })
  },
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You have a typo. Instead of upload,single(''), it should be upload.single('').

Multer will automatically parse the image and populate the req.file with the image upload data. However, in your controller, you are trying to access req.files. So, if you will upload multiple files, I would suggest that you switch from upload.singe('') to upload.any(), since upload.any() will populate req.files and not req.file.

You can change your router like this:

router
  .route('/')
  .get(profileController.get)
  .post(upload.any(), profileController.post)
  .delete(profileController.delete)
  .patch(profileController.patch)

And you can change your contoller like this:

const profileController = {
  post:(req, res) => {
    console.log(req.files)
    let file = req.files[0];
    ...
  },
}

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda