Wednesday, 10 May 2017

File Download In Node JS and Angular JS

I am trying to down a file through a Node JS application, the code follows next, HTML

<span style="color:green;font-weight:bold;cursor:pointer;" ng-click="DownloadFile(file._id)">
                    </span>

Angular JS

$scope.DownloadFile = function (id) {
            $http.get('/download/' + id).then(function (response) {

            });

Node JS

var fs = require('fs');
var path = require('path');
var mime = require('mime');
 var appDir = path.dirname(require.main.filename);
                            // console.log(appDir, 'appDir');
                            var file = appDir + '/uploads/' + doc[0].originalfilename;
                            var filename = path.basename(file);
                            var mimetype = mime.lookup(file);
                            res.setHeader('Content-disposition', 'attachment; filename=' + filename);
                            res.setHeader('Content-type', mimetype);
                            var filestream = fs.createReadStream(file);
                            filestream.pipe(res);

All code works good no error but the file does not download. Also if i call the same Node JS code though a direct call to REST API, it downloads, but does not download if the call to the REST API is made through Angular $http object.



via user5740953

No comments:

Post a Comment