Friday 27 October 2017

javascript - How to download an xlsx in angular from express

itemprop="text">


I am generating an
xlsx file based on some user input in
express. The info is submitted via a
post request and I wanted to return the content of the file via
res.download(...).



If I
do that I get "garbage" in the data field of my
ajax response.



I tried
to prompt a download using href="https://stackoverflow.com/questions/16514509/how-do-you-serve-a-file-for-download-with-angularjs-or-javascript">this
solution, but the content is still
"garbage".



This is my angular
controller:




$scope.generateSoldGoodsReport
= function() {

reportService.generateSoldGoodsReport({

startDate: $scope.startDate,
endDate: $scope.endDate
})

.then(function(report){
var blob = new Blob([ report ], { type :
'application/xlsx' });
$scope.url = (window.URL ||
window.webkitURL).createObjectURL( blob );
})

}



and here is my
service:




generateSoldGoodsReport:
function (dates) {
var deferred = $q.defer()


$http.post('/api/secure/generateSoldGoodsReport', dates)

.then(function(response){

deferred.resolve(response.data)

})
return
deferred.promise
}


and
here is my server side
code:




sendFileResponse = function
(res) {
return function (err, fileDetails) {

if
(err)
{
res.json({
error: 1,
message:
err.message,
detailed: err.errors
})
}

else
{

res.download(fileDetails.path + '/' +
fileDetails.fileName)
}
}

}

itemprop="text">
class="normal">Answer



In the end
I ended up using a solution where in a post request I generated
the report and when the response was sent to the client I made a
get request to a predefined place where the generated report
was stored. I don't like this solution because I use two requests instead of
one.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...