Download corrupted with Nodejs

Asked

Viewed 124 times

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);
           }
      });
    }
  });
  • Set ''.

  • The file does not open, viewing by a text editor, it is perceived that there is data (using an image as an example).

  • Are the two files (the original and the received by the server) the same size? Have you opened them in a binary comparison tool like vbindiff? This can.

  • The server is still running local, so in its origin the file is perfect and opening normally, however, the download comes corrupted. I have tested with all types of files and gives in it. Making binary comparison, it just gets explicit that it is not being written correctly. I believe it is the way I am writing these files due to the fact that it works perfectly by Postman.

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

Grateful for the Attention!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.