I am trying to download the file from expressjs backend using Axios. The file is of size 1kB but on attempting to download it every time, I am getting 17 bytes file that does not open.
Here is my backend code:
const __dirname = path.resolve();
app.get("/download", function(req, res, next) {
const dirPath = `${__dirname}/images/${req.query.dir}/output`;
let files = fs.readdirSync(dirPath);
res.download(`${dirPath}/${files[0]}`);
res.status(200).send("Download complete");
});
And my frontend code is:
axios({
url: `http://example.com/download?dir=${someDir}`,
method: "GET",
responseType: "blob"
})
.then(res => {
//console.log(res.data);
const href = URL.createObjectURL(res.data);
//console.log(href);
const link = document.createElement("a");
link.href = href;
link.setAttribute("download", output.jpeg);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(href);
})
.catch(er => console.log(er));
I am puzzled to find the root cause of this. Help on this appreciated