1

I am trying to download a CSV file from the server to a client machine via a jQuery Ajax call, but for some reason the return response is not triggering the download. I know that there are several other questions which are quite similar, however, none of them are specifically using ajax with Django (that I've found), so I'm not sure if something needs to be done differently. The closest thing I could find was this one: download file using an ajax request which sets the window.location to a download.php file on success, but that doesn't really seem applicable. Everything I've been able to find, including the django documentation, uses some method that is very similar to what I have and yet every variation I've tried produces more or less the same result - nothing gets downloaded.

I've confirmed that each step of the process is executing correctly except for the last one in the views.py.

download_page.html:

{% extends 'base.html' %}
{% load staticfiles %}

<script>
    $(function() {
        $('#download').on('click', function () {
            var pk = $(this).val();
            $.ajax({
                url: '/ajax/download/',
                data: {'pk': pk}
            });
        });
    });
</script>

{% block body %}
      ...

<button id="download" value="{{ view_id }}">Download</button>
      ...

{% endblock %}

urls.py:

urlpatterns = [
      ...
    url(r'^ajax/download/', views.download, name='download'),
      ...
]

views.py:

import pathlib2
from django.http import HttpResponse
from src.apps.main.models import DataModel

def download(request):

    pk = request.GET.get('pk', None)
    fname, fpath = DataModel.export_to_csv(pk) # does the export and returns fullpath to file

    if pathlib2.Path(fpath).exists():
        file_download = open(fpath, 'r')
        response = HttpResponse(file_download, content_type='application/csv')
        response['Content-Disposition'] = 'attachment; filename="{}"'.format(fname)
        return response

It gets all the way to the point at which it should return the response and then nothing happens. There are no warnings or errors, it just seems to silently finish without ever triggering the download on the client side. I'm guessing that there's something I need to do differently to return the file, but I've not been able to determine what that is.

asdf
  • 23
  • 6

1 Answers1

0

maybe could do fname of you are a path

response['Content-Disposition'] = 'attachment; filename="{}"'.format(fname)

you can try:

response['Content-Type'] = 'application/force-download'
response['Content-Disposition'] = 'attachment; filename="donwload.scv"'

note: you can edit the filename accordingly.

DuyDQ
  • 9
  • 1