Skip to content

Instantly share code, notes, and snippets.

@gordey4doronin
Forked from DavidMah/filedownloader.js
Last active April 20, 2016 09:23
Show Gist options
  • Save gordey4doronin/1ea0f9ed2a6886ef527d to your computer and use it in GitHub Desktop.
Save gordey4doronin/1ea0f9ed2a6886ef527d to your computer and use it in GitHub Desktop.
File Download requests using jquery/POST request with psuedo ajax
// Takes an URL and object to pass to the server.
// Sends to the server. The server can respond with binary data to download.
jQuery.download = function(url, object) {
// Build a form
var form = $('<form></form>').attr('action', url).attr('method', 'post');
var keyValuePairs = jQuery.param(object).split('&').map(function(x) {
var splitted = x.split('=');
return {
key: decodeURIComponent(splitted[0]),
value: decodeURIComponent(splitted[1])
};
});
// Add key/value pairs to the form
keyValuePairs.forEach(function(x) {
// Add the key/value
form.append($('<input></input>')
.attr('type', 'hidden')
.attr('name', x.key)
.attr('value', x.value));
});
// Send request by submitting the form, then remove it
form.appendTo('body').submit().remove();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment