Download corrupted with NodeJS

0

I created a server with ExpressJS where I upload and download various files:

FileController.prototype.downloadFile = function(req, res) {
      var filePath = "./upload/" + req.body.pasta + '/' + req.body.file;
      res.download(filePath, function(err){
      });
}

By postman the download works perfectly, however, by my system the file gets corrupted.

$scope.downloadFileWeb = function() {
  var options = { method: 'POST',
    url: webServiceControl.serverAccessInfo.host + 'download',
    headers:
     { 'x-access-token': webServiceControl.accessToken,
       'content-type': 'application/x-www-form-urlencoded' },
    form:
     { pasta: $scope.manualSelecionado.idFS,
       file: $scope.arquivoSelecionado } };

  request(options, function (error, response, body) {
    if (error)  {
      console.log(error)
      throw new Error(error)
    } else {
      var path = './media/' + $scope.arquivoSelecionado;

      fs.writeFileSync(path, body, function(error) {
           if (error) {
             console.error("write error:  " + error.message);
           } else {
             console.log("Successful Write to " + path);
           }
      });
    }
  });
    
asked by anonymous 18.09.2017 / 17:55

1 answer

0

Solved, the problem was the way I was writing the file, as below:

  $scope.downloadFileWeb = function() {
      var options = {
        method: 'POST',
        url: webServiceControl.serverAccessInfo.host + 'download',
        headers:
         { 'x-access-token': webServiceControl.accessToken,
           'content-type': 'application/x-www-form-urlencoded' },
        form:
         { pasta: $scope.manualSelecionado.idFS,
           file: $scope.arquivoSelecionado } };;

      var path = './media/' + $scope.arquivoSelecionado;
      var r = request(options);

      r.on('response',  function (res) {
        res.pipe( fs.createWriteStream( path ));
      });
    }

Thank you for your attention!

    
18.09.2017 / 20:00