2016-03-08 93 views
2

我已经使用json2xlsx npm模块生成/导出xlsx文件并下载该文件我正在使用res.download(file)功能的express.js文件没有下载express.js res.download

参考:Download a file from NodeJS Server using Express

以下是我的代码:

var fs = require("fs"); 
var json2xls = require('json2xls'); 

app.use(json2xls.middleware); 

app.get('/export/:id', function (req, res) { 
    var id = req.params.id; 
    db.collection('provider').findOne({_id: mongojs.ObjectId(id)}, function (err, doc) { 
     var jsonArr = {}; 
     var arr = jsonArr = doc; 
     var xls = json2xls(arr); 
     fs.writeFileSync('data.xlsx', xls, 'binary'); //file exported 

     //Now I want to download that file 
     res.setHeader('Content-disposition', 'attachment; filename=data.xlsx'); 
     res.setHeader('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); 
     res.download(__dirname + '/public/data.xlsx', function (error) { 
      console.log(error); 
     }); 

     //res.json(doc); 
    }); 
}); 

查看HTML

 <div class="panel-body"> 

      <div class="form-group" ng-repeat="(key,value) in providerList" ng-if="!$first">      
        <label>{{key.replace("_", " ") | uppercase}}</label> 
        <input type="text" class="form-control" id="title" placeholder="Enter Title" ng-model="providerList[key]">      
      </div> 

      <div class="well well-lg text-center bg-gray">           
       <button class="btn-lg btn-success" ng-click="export(id)">Export to Spreadsheet</button> 
      </div> 
     </div> 

AngularJS控制器代码:

$scope.export = function (id) { 
      $http.put('/export/' + id, $scope.providerList).success(function (response) { 
       if (response) { 
        alert("File is successfully exported at: "+ response); 
       } 
      }); 
     }; 

埃罗R:{ [Error: Request aborted] code: 'ECONNABORTED' }

更新错误

enter image description here

任何帮助,将不胜感激。

+0

必要调试信息。 “不下载”是什么意思?任何错误?这个调用将显示在控制台中:'res.download(__ dirname +'/data.xlsx',function(error){console.log(error)});'? –

+0

这是错误:'{[错误:请求中止]代码:'ECONNABORTED'}' – Sky

+0

@ stdob--:更新后请检查 – Sky

回答

3

设置响应头前res.download()

res.setHeader('Content-disposition', 'attachment; filename=data.xlsx'); 
res.setHeader('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); 
res.download(__dirname + '/data.xlsx'); 

UPDATE:

json2xls, 您可以使用res.xls('data.xlsx', jsonArr);

对于您必须设置中间件json2xls

app.use(json2xls.middleware); 

更新2:

对于前端(AngularJS),参见this

+0

我试过,但没有工作 – Sky

+0

data.xlsx正在生成? – Jay

+0

更新后请检查 – Sky

1

可能是您的.xlsx文件保存在根文件夹中。因此,将.xlsx文件移动到public文件夹中并启用它,如下所示。

 app.use(express.static('./public')); 
+0

移动到'public'并使用'app.use(express.static(__ dirname +“/ public”)); // express.static意味着我们正在告诉服务器寻找静态文件,例如html,css,js等,但仍然不起作用 ' – Sky

+0

这里是代码现在:'res.download(__ dirname +'/public/data.xlsx ');' – Sky

+0

它没有显示任何错误,但下载也不起作用 – Sky