Roman Rdgz
Roman Rdgz

Reputation: 13254

Downloading simple text file in Django

I'm trying to serve a simple text file with Django without success so far. I think that my Django code is OK:

def status(request):
    # Get data from database
    parameters = get_parameters_from_database()
    if request.method == "GET":
        // Stuff here to render the view for a GET request
        return render_to_response('myapp/status.html', {'page_name': 'status', 'parameters' : parameters})

    elif request.method == "POST":
        if request.POST['request_name'] == 'download_txt':
            file_path = parameters['file_path']
            with open(file_path, 'rb') as fsock:
                response = HttpResponse()
                response['content_type'] = 'text/plain'
                response['Content-Disposition'] = 'attachment; filename=current.txt'
                response.write(fsock.read())
                print(response)
                return response

When the POST request is received, it get the following printed in webserver console, so I think it's ok:

<HttpResponse status_code=200, "text/html; charset=utf-8">

So I think the problema is that I am not handling the success event in Jquery's Ajax method:

$('#downloadButton').click(function(){
    $.ajax({
      url: '',
      method: 'POST',
      data: {
        request_name: 'download_txt'
      },
      success: function (data) {        
        //TODO
      },
      error: function (err) {
        console.log('Error downloading file');
      }
    });
});

The problem is that I have no idea of how I should handle the success event: I thought that the browser would automatically download the file once the server answered with that content_type

Any help?

Upvotes: 2

Views: 5380

Answers (3)

anjaneyulubatta505
anjaneyulubatta505

Reputation: 11665

without ajax simply return httpresponse with file attachment

from django.http import HttpResponse

def my_view(request):
   # some code
   file_data = "some text"
   response = HttpResponse(file_data, content_type='application/text charset=utf-8')
   response['Content-Disposition'] = 'attachment; filename="foo.txt"'
   return response

Upvotes: 8

Qback
Qback

Reputation: 4908

Browser won't automatically do anything with your data. You have to manually create downloadable element and fill it with your data. Here's also an article how to download data with javascript.

Try that (No neeed to use any library):

$('#downloadButton').click(function(){
    $.ajax({
      url: '',
      method: 'POST',
      data: {
        request_name: 'download_txt'
      },
      success: function (data) {        
          var element = document.createElement('a');
          element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(data));
          element.setAttribute('download', 'my-file-name');

          element.style.display = 'none';
          document.body.appendChild(element);

          element.click();

          document.body.removeChild(element);
      },
      error: function (err) {
        console.log('Error downloading file');
      }
    });
});

Upvotes: 2

Harsh
Harsh

Reputation: 253

You can use FileSaver library to save the file. Here's how to do it:

success: function (data) {
    var FileSaver = require('file-saver');
    var blob = new Blob([data], {type: "text/plain;charset=utf-8"});
    FileSaver.saveAs(blob, "filename.txt");
},

Upvotes: 0

Related Questions