简体   繁体   中英

How to create a downloadable link in react and express

I have a react app in which I have a button. Basically a div.

This is returned from my Button Component and everything else are props.

<button className={"button "+styleButton} onClick={handleClick}>
    {source && <img src={source} alt={alt} className={"image "+styleImage} /> }
    <h3 className="text">{children}</h3>
</button>

Now what I did when someone clicks this Button(div) is:

const handleClick = () => {
    console.log('downloading...');
    let a = document.createElement('a');
    a.href = '192.168.43.102/download/brief';
    a.download = 'brief.pdf';
    a.click();
}

On clicking on that div, I want a pdf to be downloaded on the client side. There are hundreds to ways on the internet. Some send a request with(axios) and download on front-end and then create a downloadable link and some just use an anchor tag.

I tried some of these but I can't make it working. Also on the express side.

This route is my express side:

const router = require('express').Router();
const { Router } = require('express');
const path = require('path');
const { route } = require('./api');

const brief = path.join(__dirname, '..', '/public/resources/krishi-brief.pdf');
const uml = path.join(__dirname, '..', '/public/resources/krishi-uml.pdf');

router.get('/brief', (req, res) => {
    res.sendFile(brief);
});

router.get('/uml', (req, res) => {
    res.download(uml);
});

router.get('/proposal', (req, res) => {
    res.send("Not found");
});

router.get('/ppt', (req, res) => {
    res.send("Not found");
});

module.exports = router;

I have a very good pfd which is non-corrupted but when I get the file, it is corrupted because none of the applications can open it.

I also tried:

router.get('/uml', (req, res) => {
    res.set({
      'Content-Type': 'application/pdf'
    })
    res.download(uml);
});

But now I am confused about the implementation and also if this is the right way.

Please tell me if this is the right(professional) way to do this in react app and where is it wrong? I am only getting corrupted file:(

OK so when I click on the download, the server 192.168.43.102 should be written as http://192.168.43.102 and the anchor tag won't give or throw and error but just download something which I am not sure about which is not even on your route.

Basic thing I was struggling on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM