javascript – How to download the csv file by ajax-ThrowExceptions

Exception or error:
$.ajax({
    type: "GET",
    url: url,
    success: function(response) {
        console.log(response);// successfully got the csv,but,,,how can I download???
    }
});

I set the csv_view in python server side view.py

def csv_view(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=somefilename.csv'

    writer = csv.writer(response)
    writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])
    return response
How to solve:

You can try this using Blob api:

const DownloadCsv = (function() {
  const a = document.createElement("a");
  document.body.appendChild(a);
  a.style = "display: none";
  return function(data, fileName) {
    const blob = new Blob([data], {type: "octet/stream"}),
      url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
  };
}());

$.ajax({
  type: "GET",
  url: url,
  success: function(response) {
    //console.log(response);
    DownloadCsv(response, 'somefilename.csv')
  }
});

Leave a Reply

Your email address will not be published. Required fields are marked *