Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
Trying to serve a file and automatically start a download with Express

Seems like many people have ran into similar kind of problem but googling hasn't helped me so far. I'm trying to serve the file to the user and automatically prompt download on client side, but all I'm getting is "The image cannot be displayed because it contains errors.

Here is my client side code:

function downloadFile(passcode){
  console.log(passcode);
  const payload = {"password" : passcode.toLowerCase()}
  axios.post(downloadUrl, payload, {
    headers : {'Content-Type' : 'application/json'}
  })
  .then((res) => {
    console.log(res.data)
    window.open(downloadUrl + '/' + res.data)
  })
}

So the user types in a passcode, and clicks on the download button and should get the appropriate file. New tab opens but file doesn't stard downloading. Here is my server side:

const getFilePath = async (req, res) => {
    const passcode = req.body.password
    try {
        fs.readdir(path.join(homeDir + '/uploads/' + passcode), 'utf-8',(err, files) => {
            files.forEach((file) => {
                const filename = passcode + '/' + file
                try {
                    res.send(filename)
                    res.end()
                } catch (error) {
                    console.log(error);
                }
            })   
        })
    } catch (error) {
        console.log(error);
    }
}

const fileDownload = async (req, res) => {
    const {dir: directory, file: fileName} = req.params
    const filePath = path.join(homeDir + '/uploads/' + directory + '/' + fileName)
    fs.access(filePath, fs.constants.F_OK, err => {
        //check that we can access  the file
        console.log(`${filePath} ${err ? "does not exist" : "exists"}`);
      });
    res.download(filePath)
    res.end()
}

I even check the file with fs.access and it returns true (it prints {filepath} exists), but the file is not served at all.

Any kind of help is much appreciated!

EDIT: Decided to work on my front end a bit to cool off, came back and immidiatelly noticed res.end() just below send file, which ends the transmission. Removed it and it works like a charm!

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda