Res.download()传递数据而不是下载文件

时间:2018-12-26 21:23:30

标签: angularjs node.js express

我试图将NodeJS服务器生成的文件作为可下载文件从服务器传递到客户端。

我的用户正在填充对象数据,然后将其存储在DB中,创建文件的功能将读取对象以将数据填充到生成的文件中。该文件包含十六进制数据(如果需要的话)。现在,用户将选择所需的对象,将其分组为对象数组,单击前端的按钮后,POST请求将数组发送至后端以生成文件(此方法有效) ,在生成文件后,我检查以确保文件存在(确实存在),然后尝试使用res.download('filepath / filename','downloadedname')将其发送回前端(此操作不导致文件下载,但确实发送了res,我认为这是res.data中文件的预期内容

完整代码流: AngularJS控制器:

 function DialogController($scope, $mdDialog, DashFactory, recipeBookService) {
  $scope.recipes = [];
  $scope.book = recipeBookService.getBook();
  for(i=0; i<$scope.book.length; i++){
    DashFactory.getRecipe($scope.book[i], function(data){
      $scope.recipes.push(data);
    });
  }
  $scope.empty = function(book) {
    $scope.book = recipeBookService.clearBook();
    $mdDialog.cancel();
  };
  $scope.generate = function(recipes){
    DashFactory.generateFile(recipes)
  }

  $scope.delete = function(index){
    $scope.recipes.splice(index, 1);
  };
}

AngularJS工厂:

factory.generateFile = function(recipes, callback){
  console.log('factory recieved recipes', recipes);
  $http({
    url: '/createFile',
    method: 'POST',
    data: recipes
  }).then(function(res){
    console.log('success', res);
  },function(res){
    console.log('err', res);
  })
}

节点服务器(相关部分)

const fs = require('fs');
createFile: function(req,res){
    console.log('server reciped recipes', req.body);
    if (createRecipeFile.writeRecipe(req.body)){
        fs.access('server/generatedFiles/RecipeTest.REL', fs.constants.R_OK, (err) => {
      console.log(`${'server/generatedFiles/RecipeTest.REL'} ${err ? 'is not readable' : 'is readable'}`);
        res.download('server/generatedFiles/RecipeTest.REL', "G4R12.REL")
        });

    } else {
        console.log('file creation failed');
        res.sendStatus(500);
    }

}

预期结果,是将文件server / generatedFiles / RecipeTest.REL下载为G4R12.REL,当前结果是chrome记录的res,如下所示:

{data: "↵&2B����LX����… 
������������������������������{g]U", status: 
200, headers: ƒ, config: {…}, statusText: "OK", …}
config:
data: Array(2)
0: {_id: "5be60e3d8bf74d716c2f5e1b", updatedAt: "2018-11-09T22:46:21.445Z", 
createdAt: "2018-11-09T22:46:21.445Z", name: "Gemini Twin 3 Batch 11-9 2:45", brewerName: "Gemini", …}
1: {_id: "5be60eb58bf74d716c2f5e1c", updatedAt: "2018-11-09T22:48:21.443Z", createdAt: "2018-11-09T22:48:21.443Z", name: "Gemini Twin 3 Batch 11-9 2:45", brewerName: "Gemini", …}
length: 2
__proto__: Array(0)
headers: {Accept: "application/json, text/plain, */*", Content-Type: "application/json;charset=utf-8", Authorization: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoid…Dc5fQ.JPVQkZUaJ2651gyC1_L5jTiLQGAy3PxNjPbAGrPkm4s"}
jsonpCallbackParam: "callback"
method: "POST"
paramSerializer: ƒ (a)
transformRequest: [ƒ]
transformResponse: [ƒ]
url: "/createFile"
__proto__: Object
data: "↵&2B����LX�������=s�����}]=  �  �↵��}
]=����}�����������������������������������������������������������������������������{g]U"
headers: ƒ (d)
status: 200
statusText: "OK"
xhrStatus: "complete"
__proto__: Object

1 个答案:

答案 0 :(得分:0)

通过将数据而不是res.download传递到前端来解决此问题,并告诉angularjs期望http请求res中出现blob

节点服务器

createFile: function(req,res){
    console.log('server reciped recipes', req.body[0], req.body[1]);
    console.log('from user', req.body[1]);
    createRecipeFile.writeRecipe(req.body[0], req.body[1])
    user = req.body[1];
        var file = 'server/generatedFiles/'+user+'.REL'
        fs.access(file, fs.constants.R_OK, (err) => {
                if (err){
                    console.log('err', err);
                } else{
            var count = 0
                console.log('reading stream');
                var fReadStream = fs.createReadStream(file);
                fReadStream.pipe(res);
            }
        })
},

AngularJS工厂

factory.generateFile = function(recipes, user, callback){
  console.log('factory recieved recipes', recipes, user);
  $http({
    url: '/createFile',
    method: 'POST',
    data: [recipes, user],
    responseType: 'blob'
  }).then(function(res){
    console.log('generate file res1', res, res.data);
    console.log('recieved data length', res.data.length);
    var file = res.data;
    FileSaver.saveAs(file, 'g4R12.REL')
  },function(res){
    console.log('generate file res2', res);
  })
}