How to download a .docx file in AngularJs controller from Node.js

I've been looking in stackoverflow for some answer but I didn't succeed.

I have a node.js method in routes which generates a .docx template from another template with docxtemplater library.

I send a post from angularjs to my /api/generateReport with some data and I generate this .docx but I cant manage to send it. It is not recommendable nor secure placing the file in /public dir but I can't download it if I place the file in /public dir and I provide the file path to AngularJs.

I've read about blob and other stuff but I can't manage to download a .docx file.

PS: I'm using $resource directive to handle api requests and I have set responseType to arrayBuffer

angular.module('MyApp')
  .factory('GenerateReport', function($http, $location,$resource, $rootScope, $alert, $window) {

       return $resource("/api/GenerateReport/:id",{}, {
            'query': {
                method: 'GET',
                isArray: false
            },
            responseType: 'arrayBuffer'
        });

  });

I send the response this way.

 var fileDocx = fs.readFileSync(__base + "/plantillaSalida.docx", "binary");
 res.send(fileDocx);

Response is received in angular controller:

GenerateReport.save({
  projectExecution: $scope.projectExecution,
  auditingProject: $scope.auditingProject,
  participants: $scope.participants,
  exampleProjects: $scope.exampleProjects
  
  }, function(response) {

/***What to to here??***/

    $mdToast.show(
    $mdToast.simple()
    .content('Informe generado')
    .position('bottom right left')
    .hideDelay(3000)
    );
  },
  function(error) {
    console.log("error");
    $mdToast.show(
    $mdToast.simple()
    .content('Error al general el informe')
    .position('bottom right left')
    .hideDelay(3000)
    );
  }
);

Upvotes: 3

Views: 2976

Answers (1)

Subash Selvaraj
Subash Selvaraj

Reputation: 3385

I would suggest to add download header to your file and link it using hyperlink (<a href="/download">)

var path = require('path');
var mime = require('mime');

app.get('/download', function(req, res){

  var file = __base + "/plantillaSalida.docx";

  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);
});

If you are using express use below code

app.get('/download', function(req, res){
    var file = __base + "/plantillaSalida.docx";
    var filename = path.basename(file);
    res.setHeader('Content-disposition', 'attachment; filename=' + filename);
    res.download(file); 
 });

Upvotes: 0

Related Questions