0

I am working with the GUI where there is a button. On button click, an ajax call happens which returns a JSON to the backend in Django's view.py. On the basis of the JSON, I am creating an excel file and the path of this file is returned to the place where ajax call happened. I want that file to download on the click of the same button.

i.e, is it possible to do all these operations (from ajax call to download the excel file) with one click of that button?

edit

Path means the physical path of file system.

bSr
  • 1,410
  • 3
  • 16
  • 30
  • When you say path, you means the file URL? – Simon Bruneaud May 16 '18 at 11:28
  • @SimonBruneaud path is machine's file system path. – bSr May 16 '18 at 11:31
  • I guess the excel file is created and stored on server side. So your users won't be able to access the path because it's not on their local machine. If the purpose of this project is only to create with a local web server you still can get a file from your browser doing this: https://stackoverflow.com/questions/14052473/go-to-local-url-with-javascript – Simon Bruneaud May 16 '18 at 11:34

1 Answers1

0

Yes it is possible to do so. Just make sure that the file is served from your STATIC_URL location ('static' folder by default). In your views.py,

def download(request):
    # /static/ is your STATIC_URL in settings
    file_path = "/static/xxxx.txt" # file path
    return JsonResponse({"file_path": file_path})

In your ajax code,

xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.status == 200) {
      window.location = this.file_path;
    }
};
xhttp.open("GET", "/download", true);
xhttp.send(); 
Shivam Singh
  • 1,584
  • 1
  • 10
  • 9
  • do we need to create a url in urls.py file for '/download' ? The error I am getting at server side is 'Not Found: /download' and client side 'Failed to load resource: the server responded with a status of 404 (Not Found)' – bSr May 16 '18 at 12:01
  • Yes, you have to define a url for that view – Shivam Singh May 16 '18 at 12:02