Last active
January 23, 2018 11:32
-
-
Save atiq1589/445a3c7f43d57e09946f1d3f38c0d105 to your computer and use it in GitHub Desktop.
Create CSV and upload it to server with AngularJs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Post(url, data, options) { | |
var deferred = $q.defer(); | |
$http.post(url, data, options) | |
.success(function(res) { | |
deferred.resolve(res); | |
}).error(function(error, status) { | |
deferred.reject({ error: error, status: status }); | |
}); | |
return deferred.promise; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function JsonToCsv(json, keys) { | |
var fields = []; | |
if (keys) { | |
fields = Object.keys(keys); | |
} else { | |
fields = Object.keys(json[0]); | |
} | |
var replacer = function(key, value) { return value == null ? '' : value; }; | |
var csv = json.map(function(row) { | |
return fields.map(function(name) { | |
return JSON.stringify(row[name], replacer); | |
}).join(','); | |
}); | |
csv.unshift(fields.join(',')); | |
csv = csv.join('\r\n'); | |
return csv; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var jsonData = {}; | |
var fileName = 'your_file_name.extension'; | |
var csv = JsonToCsv(jsonData); | |
var file = new Blob([csv], { type: 'application/octet-stream' }); | |
var data = new FormData(); | |
data.append('file', file, fileName); | |
Post('url/to/upload/', data,{ | |
transformRequest: angular.identity, | |
headers: { | |
'Content-Type': undefined | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment