title: Download a file in django with a button using xmlhttprequest
body: <p>I looked at many same questions but none resolved my problem,
  I'm trying to download a file generated in my view using a button.
  Problem : I get an empty file while clicking on download button</p>
  
  <p>My view:</p>
  
  <pre><code>class dumpView(View):
  
  template_name = 'download.html'
  def get(self, request):
      file = open("/home/test.pdf", "rwbt")
      response = HttpResponse(file.read(), content_type="application/pdf")
      response['Content-Disposition'] = 'attachement; filename=%s' % file
      return render(request, 'download.html')
  </code></pre>
  
  <p>My url:</p>
  
  <pre><code>url(r'^dump/', dumpView.as_view()),
  </code></pre>
  
  <p>My template:</p>
  
  <pre><code> {% extends 'base.html' %} 
   {% load staticfiles %} 
   {% block content %}
   &lt;div class="container"&gt;
   &lt;div class="row"&gt;
      &lt;div class="jumbotron"&gt;
          &lt;div class="row"&gt;
              &lt;center&gt;
                  &lt;a href="javascript:void(0)" class="btn btn-primary btn-lg dump"&gt;Download&lt;/a&gt;
              &lt;/center&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  &lt;/div&gt;
  {% endblock %} 
  {% block javascript %}
  &lt;script src="{% static 'js/home.js' %}"&gt;&lt;/script&gt;
  {% endblock %}
  </code></pre>
  
  <p>My Django view is rendering the response. I did add an on click handler to the button with class dump in the UI to make a XHR request to the “/dump” URL  and recieve response as a blob and download the file with custom name and date.</p>
  
  <p>My js :</p>
  
  <pre><code>$(".dump").on("click", function() {
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
      var a, today;
      if (xhttp.readyState === 4 &amp;&amp; xhttp.status === 200) {
          a = document.createElement('a');
          a.href = window.URL.createObjectURL(xhttp.response);
          today = new Date();
          a.download = "file_" + today.toDateString().split(" ").join("_") + ".pdf";
          a.style.display = 'none';
          document.body.appendChild(a);
          return a.click();
      }
  };
  xhttp.open("GET", "/dump", true);
  xhttp.setRequestHeader("Content-Type", "application/json");
  xhttp.responseType = 'blob';
  xhttp.send();
  });
  </code></pre>