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

248
Views
How to send a file (Any type) to the frontend from the express server?

I am taking a file which is stored on the server, and sending it to the frontend for download. So when the user hits this url, it the file should automatically download. And it is downloading also. But the problem is the file recieved is corrupt. Like If I am sending some pdf from the server, I am getting a corrupt pdf.

Let me explain what the code below does, it takes the unique id (uuid) from the url params and then searches for a file with that particular uuid, if the file is not there it sends an error, but if it is there, it searches for the file on the server using the uuid and the path mentioned the db doc, and then sends it to the frontend. But when I am downloading that file I am getting a corrupt file.

Also this happens when I hit this endpoint of the server which I hosted on heroku, but the file downloaded is not corrupt when I use the localhost...which I think is obvious. Please help.

Code :

import express from 'express' ; 
import File from '../models/file.js' ; 
import path from 'path' ; 

const router = express.Router() ; 

router.get('/:uuid', async (req,res)=> {

    const file = await File.findOne({uuid: req.params.uuid});

    if(!file) return res.render('download', {error: "Link expire ho gya"});
    console.log(file)
    const __dirname = path.resolve();

    console.log(__dirname) ; 

    const filePath = `${__dirname}\\${file.path}`;
    console.log(filePath) ; 
    res.download(filePath) ; 
    

})

export default {router}
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!