简体   繁体   中英

How to set up a file download dialog using Django and jQuery?

I am jQuery newbie and I have been trying to set up a file download dialog window without any success. If and when the dialog window is loaded, the user should have the option to download the dynamically generated file. I am not able to set up a dialog window.

On debugging, I can see that a valid http response is generated. Generated content disposition data is given below:

 attachment; filename=foo.csv

Use Case:

My application is a Django web app used to display the data fetched from the database on a django template. I want to provide the ability to download the displayed data in a csv format when required if the user clicks on a button with text 'Export To Csv'

Code

Javascript/Html

/**
 * Creates a file to be downloaded upon clicking a button.
 */
 $('button[id*="ExportToCsv"]').click(function() {
    var report_type = $(this).attr('id').split('ExportToCsv')[0];
    // var report_date = '{{ report_date }}'.split('-');
    $.ajax({
        url: '/reports/' + report_type + '/export_to_csv/',
        type: 'POST',
        mimeType: 'text/csv',
        data: {'report_date': '{{ report_date }}'},
        success: function(data) {
            return data;
        }
    });
 });

Html:

<button id = "ExportToCsv">Export To Csv</button>

Django:

class CsvOutputResponse(object):
  """Handles a csv file attachment object.

  Attributes:
    filename: String name of the csv file.
    response: HttpResponse object.
    writer: Csv writer object.
  """

def __init__(self, filename):
  """Initalizes the CsvOutputResponse class.

   Args:
     filename: String name of the csv file.
   """
   self.filename = filename
   self.response = self._InitializeResponse()
   self.writer = csv.writer(self.response)

def _InitializeResponse(self):
  """Initialize a csv HttpResponse object.

  Returns:
    HttpResponse object.
  """
  response = django_dep.HttpResponse(mimetype='text/csv')
  response['Content-Disposition'] = (
      'attachment; filename=%s.csv' % self.filename)
  return response

def WriteRow(self, content):
  """Write a single row to the csv file.

  Args:
    content: List of strings of csv field values.
  """
  self.writer.writerow(content)

def WriteRows(self, content):
  """Write multiple row to the csv file.

  Args:
    content: List of lists of strings of csv field values.
  """
  self.writer.writerows(content)

def GetCsvResponse(self):
  """Get the csv HttpResponse object.

  Returns:
    content: HttpResponse object.
  """
  return self.response

urls.py

(r'^reports/(?P<report_type>\w+)/export_to_csv/$',
 'myproject.myapp.views.ExportTab')

views.py

def ExportTab(request, report_type):
  """Generates a file to be exported and made available for download.

  Args:
    request: HttpRequest object.
    report_type: String type of report to be generated.

  Returns:
    HttpResponse object.
  """
  report_date = request.POST['report_date']
  db = database.Database()
  if report_type == 'Trailing':
    reports = containers.GetTrailingReports()
  elif report_type == 'Ytd':
    reports = containers.GetYtdReports()
  return CsvOutputResponse('foo.txt').writeRows(reports).GetCsvResponse()

Instead of performing the POST in AJAX, have the browser navigate to the view naturally. The browser will then prompt for the download.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM