Reputation: 7404
I've generated/exported a xlsx
file using json2xlsx
npm module and to download that file I'm using res.download(file)
functionality of of express.js
.
Reference: Download a file from NodeJS Server using Express
Following is my code:
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);
});
});
View 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 controller code:
$scope.export = function (id) {
$http.put('/export/' + id, $scope.providerList).success(function (response) {
if (response) {
alert("File is successfully exported at: "+ response);
}
});
};
Error: { [Error: Request aborted] code: 'ECONNABORTED' }
Updated Error
Any help would be appreciated.
Upvotes: 4
Views: 12267
Reputation: 1
I notice your angular controller makes a $http.put
but your backend is expecting a GET (app.get
). Are you sure this is how you intended to configure it?
Upvotes: 0
Reputation: 1615
Set response header before 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:
According to json2xls,
you can use res.xls('data.xlsx', jsonArr);
.
For that you have to setup middleware for json2xls
app.use(json2xls.middleware);
UPDATE 2:
For front end(AngularJS), Refer this
Upvotes: 6
Reputation: 598
May be your .xlsx file saved in the root folder.So, moved the .xlsx file under public folder and enable it in express like below.
app.use(express.static('./public'));
Upvotes: 1