Flask+AngularJS Http Post Download file

  1. Download csv file

Server Side:

@userprogressreport.route(‘/filedownload’, methods=[‘POST’])
def filedownload():
csv = “”””REVIEW_DATE”,”AUTHOR”,”ISBN”,”DISCOUNTED_PRICE”
“1985/01/21″,”Douglas Adams”,0345391802,5.95
“1990/01/12″,”Douglas Hofstadter”,0465026567,9.95
“1998/07/15”,”Timothy “”The Parser”” Campbell”,0968411304,18.99
“1999/12/03″,”Richard Friedman”,0060630353,5.95
“2004/10/04″,”Randel Helms”,0879755725,4.50″””
file_name = “a.csv”
response = make_response(csv)
# This is the key: Set the right header for the response
# to be downloaded, instead of just printed on the browser
response.headers[“Content-Disposition”] = “attachment; filename=”+file_name
return response

Client Side:

$scope.exportUserProgressData = function () {
var params = $scope.getQueryParameter();

$q.all([SkillStatisticsModelFactory.apiPostProxy(“exportUserProgressData”, params)]
).then(function (response) {
var blob = new Blob([response[0].data], {type: “text/plain”});
$scope.saveAs(blob, ‘File_Name’ + ‘.csv’);
}, function (err) {
//console.log(err);
});
};

$scope.saveAs = function(blob, fileName)
{
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName);
} else {
var link = document.createElement(‘a’);
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
}
}

2. download excel file

server side

@userprogressreport.route(‘/mathjoy/api/v1.0/exportUserProgressData’, methods=[‘POST’])
def export_user_progress_data():

response = excel.make_response_from_array([[1, 2], [3, 4]], “xlsx”, file_name=”export_data”)

client side

$scope.exportUserProgressData = function () {
var params = $scope.getQueryParameter();

//$q.all([SkillStatisticsModelFactory.apiPostProxy(“exportUserProgressData”, params)]
//).then(function (response) {
// //var blob = new Blob([response[0].data], {type: “text/plain”});
// //$scope.saveAs(blob, ‘my_excel’ + ‘.csv’);
// var blob = new Blob([response[0].data], {type: ‘application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’});
// $scope.saveAs(blob, ‘my_excel’ + ‘.xlsx’);
//}, function (err) {
// //console.log(err);
//});

$http({
url: ‘mathjoy/api/v1.0/exportUserProgressData’,
method: ‘POST’,
responseType: ‘arraybuffer’,
data: params,
headers: {
‘Content-type’: ‘application/json’,
‘Accept’: ‘application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’
}
}).success(function(response){
var blob = new Blob([response], {type: ‘application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’});
$scope.saveAs(blob, ‘my_excel’ + ‘.xlsx’);
}).error(function(){
//Some error log
});
};

 

 

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a comment