Friday, 12 May 2017

Node.js - jQuery. Get PDF from server and display on front-end

I'm bit stuck here. My intent is to first get all files (filenames) from a static folder + subfolders and list all on front-end.

When user clicks one of the filenames (mostly pdf's), the server returns the selected items content.

I'm able to send the pdf data as binary to front-end, but how could I display the data in a new tab with js/jQuery?

so far..

Server.js -

// Importing and initializing npm/node plugins
var app = require('express')();
var server = require('http').createServer(app);
var logger = require('morgan');
var bodyParser = require('body-parser');
var pdf = require('express-pdf');
var cors = require('cors');
var fs = require('fs');

// Import config settings
var config = require('./config.json');

app.use(logger('dev'));

// Allow application/x-www-form-urlencoded and application/json
app.use(bodyParser.urlencoded({
    extended: false
}));

app.use(bodyParser.json({
    limit: '50mb'
}));

app.use(cors());

app.use(pdf);

app.get('/getfiles', function (req, res) {
    var dir = config.sourceDir;

    var foundFiles = [];

    fs.readdir(dir, function (err, files) {
        if (err) {
            console.log('Error reading ' + dir);
            process.exit(1);
        }
        console.log('Listing files in Directory ' + dir);
        files.forEach(function (f) {
            foundFiles.push(f);
        });
        res.json(foundFiles);
    });
});

app.post('/showfiles', function (req, res) {
    var file = req.body.filename;
    var dir = config.sourceDir;
    fs.readFile(dir + file, function (err, data) {
        res.contentType('application/pdf');
        res.send(data);
    });
});

// Open server in port
server.listen(config.port, function () {
    console.log('Server listening on port: ' + config.port);
});

module.exports = app;

On front-end -

$(function () {

    getFiles();

});

function getFiles() {
    $.ajax({
        type: "GET",
        url: "http://localhost:3000/getfiles",
        contentType: "application/json; charset=utf-8",
        crossDomain: true,
        dataType: "json",
        success: function (data, status, jqXHR) {
            if (data) {
                $.each(data, function (index, value) {
                    $("#listContainer1").append("<li><a href='#' onclick='showFile(this)'>" + value + "</a></li>");
                });
            }
        },
        error: function (jqXHR, status) {
            console.log("Error fetching data");
        }
    });
}

function showFile(file) {
    $.ajax({
        type: "POST",
        data: JSON.stringify({
            "filename": $(file).text()
        }),
        url: "http://localhost:3000/showfiles",
        contentType: "application/json; charset=utf-8",
        crossDomain: true,
        dataType: "application/pdf",
        success: function (data, status, jqXHR) {
            if (data) {
                var file = new Blob([data], {
                    type: 'application/pdf'
                });
                var fileURL = URL.createObjectURL(file);
                window.open(fileURL);
            }
        },
        error: function (jqXHR, status) {
            console.log("Error showing file");
        }
    });
}

But this keeps falling into the "Error showing file" pit. :(



via Jack M.

No comments:

Post a Comment