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}