fs.readFile does not give me a correct format for pdf

3

I am trying to load a pdf in a new browser tab by passing it by res.send so that the file remains private and not accessible unless the user has the necessary permissions. The problem is that when the file pdf is opened in the browser, the content does not appear, the sheets appear blank.

The code in node.js is:

FilesController.prototype.showPdfInBrowser = function (req, res) {
var filePath = "My url"

fs.readFile(filePath , function (err,data){
    res.send(data);
});
};

And Angular's:

$scope.showPdfInBrowser = function (log) {
            $http.get(log.url)
                .then(function (data) {
                    console.log(data);

                    var file = new Blob([data.data], {type: 'application/pdf'});
                    var fileUrl = URL.createObjectURL(file);
                    window.open(fileUrl);
                })
        };
    
asked by Fzurita 12.10.2016 в 01:45
source

3 answers

1

In the end I solved the problem. Simply put what kind of data was going to receive the request in Angular.

Referring to the example that I put when publishing the question, in the part of Angular it would be necessary to put the following:

$scope.showPdfInBrowser = function (log) {
    $http.get(log.url, { responseType: 'arraybuffer' })   // <----- tipo de datos
        .then(function (data) {
            console.log(data);
            var file = new Blob([data.data], {type:'application/pdf'});
            var fileUrl = URL.createObjectURL(file);
            window.open(fileUrl);
        })
};
    
answered by 17.10.2016 в 12:28
0

I'm not sure but I think you're using express, if so you can use res.sendFile or res.sendfile (depending on the version you're using)

    
answered by 17.10.2016 в 01:31
0

if you want to give a more detailed view you can use PDF.js, you just have to add a line of code like this:

$scope.showPdfInBrowser = function (log) {
$http.get(log.url, { responseType: 'arraybuffer' })   // <----- tipo de datos
    .then(function (data) {
        console.log(data);
        var file = new Blob([data.data], {type:'application/pdf'});
        var fileUrl = URL.createObjectURL(file);
        var viewerUrl = '/Scripts/PDF.js/web/viewer.html?file=' + encodeURIComponent(fileUrl);
        window.open(viewerUrl);
    })
};

and the result would be something like this link . Greetings

    
answered by 19.10.2016 в 17:24