jQuery Tutorial to Download File as a Blob Using AJAX in all Browsers Using HTML5 & Javascript Full Project For Beginners

 

 

jquery.download.js

 

 

function() {
 var jq = jQuery || $;
 jq.download = function(settings) {
  var newSettings = jq.extend(true, {}, settings);
  var oldSuccess = settings.success || function(data) { return { fileName: "download", data: data }; };
  newSettings.success = function() {
    // { fileName: '', contentType: '', data: '' }
    var result = settings.success.apply(this, arguments);

    if (window.navigator.msSaveBlob)
      window.navigator.msSaveBlob(result.data, result.fileName);
    else
    {
      var blob = new Blob([result.data], { type: result.contentType || 'application/octet-stream' });
      var link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
      link.href = URL.createObjectURL(blob);
      link.download = result.fileName;
      link.click();
      URL.revokeObjectURL(link.href);
    }
  };

  jq.ajax(newSettings);
 };
}();

 

 

JQuery Downloader

JQuery plugin that allows for downloading files via ajax using blobs.

Supported in IE9+/Edge (4GB limit), and all other major browsers.

Usage

The parameters for JQuery.download are the same for the JQuery.ajax(settings). The only difference is the success event. Your method must return the following:

{
  filename: '', /* The name of the file */
  contentType: '' /* The content type of the file (defaults to 'application/octet-stream') */,
  data: '' /* The actual data to return */
}

Example

$(function() {
  $.download({
    url: "http://localhost/something-that-generates-a-csv",
    success: function(data) {
      return {
        fileName: "download.csv",
        contentType: "text/csv",
        data: data
      };
    },
    error: function() {
      alert("ERMAGERD!  ERT'S BRERKEN!");
    }
  });
});

Leave a Reply