How to Force Browser PDF File Download as Attachment in Browser Using Javascript & AJAX on Button Click in Node.js and Express Request or Route Response Full Project For Beginners

 

Welcome folks today in this blog post we will be forcing the browser to download the pdf file as attachment using javascript and AJAX on button click in node.js and express request or route as response.All the full source code of the application is shown below.

 

 

 

Get Started

 

 

 

In order to get started you need to install express library by using the pip command as shown below

 

 

pip install express

 

 

After installing this make a index.html file inside the node.js project and copy paste the below code

 

 

index.html

 

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport"
    content="width=device-width, initial-scale=1.0" />
<link
href=
"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity=
"sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6"
crossorigin="anonymous"
/>
</head>
<body>
<div class="container">
<button id="download" class="btn btn-primary my-5">
Download PDF
</button>
</div>
<script src=
"https://code.jquery.com/jquery-3.6.0.js"
        integrity=
"sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous">
</script>
<script src=
"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js"
        integrity=
"sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf"
crossorigin="anonymous">
</script>

<script>
$("#download").click(function (e) {
$.ajax({
    type: "GET",
    url: "/downloadPDF",
    xhrFields: {
    // specify response type as "blob" to handle objects
    responseType: "blob",
    },
    success: function (data) {

    // creating a hidden <a> tag
    var a = document.createElement("a");

    // creating a reference to the file
    var url = window.URL.createObjectURL(data);

    // setting anchor tag's href attribute to the blob's URL
    a.href = url;

    // setting anchor tag's download attribute to the filename
    a.download = "Resume.pdf";
    document.body.append(a);

    // click on the <a> tag
    a.click();

    // after clicking it, remove it from the DOM
    a.remove();
    // release an existing object URL which was previously
    // created by calling URL.createObjectURL()
    // once we have finished using an object URL, let the
    // browser know not to keep the reference to the file any longer.
    window.URL.revokeObjectURL(url);
    },
    error: function (result) {
    alert("error");
    },
});
});
</script>
</body>
</html>

 

READ  Build a Drawing Paint HTML5 Canvas App to Draw Lines,Rectangles Using Pencil in Browser Using Vanilla Javascript Full Project For Beginners

 

 

Now create a app.js file and copy paste the following code

 

 

app.js

 

 

// Load necessary packages
const express = require("express");

// create an express app
const app = express();

// define PORT number to listen to the requests
const PORT = process.env.PORT || 3000;

// to serve files from uploads directory
app.use("/uploads", express.static("uploads"));

// express routes
app.use("/", require("./routes"));

// listen to requests
app.listen(PORT, () => console.log(`Server started running on PORT ${PORT}`));

 

 

 

Now make a routes.js file and copy paste the following code

 

 

routes.js

 

 

// Load necessary packages
const express = require("express");

// express router
const router = express.Router();

// respond with index.html when a GET request is made to the homepage
router.get("/", (req, res) => {
    res.sendFile(__dirname + "/views/index.html");
});

// route for handling PDF request
router.get("/downloadPDF", (req, res) => {
    res.download("uploads/Resume.pdf");
});

// export router middleware and use it in app.js
module.exports = router;

Leave a Reply