Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!