const express = require("express"); const router = express.Router(); const fs = require("fs"); const lastFilesDir = "./public/upload/converted/"; const renderPageName = "invoice_sign"; // load the page router.get("/", function (req, res) { let lastFiles = []; if (!fs.existsSync(lastFilesDir)) { fs.mkdirSync(lastFilesDir); } const dir = fs.opendirSync(lastFilesDir); let entity; while ((entity = dir.readSync()) !== null) { if (entity.isFile()) { lastFiles.push({ type: "f", name: entity.name }); } else if (entity.isDirectory()) { lastFiles.push({ type: "d", name: entity.name }); } } res.render(renderPageName, { lastFiles }); }); //Post the upload file // For handling the upload request router.post("/", function (req, res) { // When a file has been uploaded if (req.files && Object.keys(req.files).length !== 0) { // Uploaded path const uploadedFile = req.files.uploadFile; // Logging uploading file console.log(uploadedFile); // Upload path const uploadPath = lastFilesDir; if (!fs.existsSync(uploadPath)) { fs.mkdirSync(uploadPath); } // To save the file using mv() function uploadedFile.mv(uploadPath + uploadedFile.name, function (err) { if (err) { console.log(err); res.send("Failed !!"); } else res.send("Successfully Uploaded !!"); }); } else res.send("No file uploaded !!"); }); // To handle the download file request router.get("/download", function (req, res) { // The res.download() talking file path to be downloaded // console.log(req); // res.download(__dirname + "/uploads/fax.odg", function (err) { // if (err) { // console.log(err); // } // }); const downloadFile = lastFilesDir + req.query.downloadFile; console.log(downloadFile); res.download(downloadFile, function (err) {}); }); module.exports = router;