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
My view:
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')
My url:
url(r'^dump/', dumpView.as_view()),
My template:
{% extends 'base.html' %}
{% load staticfiles %}
{% block content %}
<div class="container">
<div class="row">
<div class="jumbotron">
<div class="row">
<center>
<a href="javascript:void(0)" class="btn btn-primary btn-lg dump">Download</a>
</center>
</div>
</div>
</div>
</div>
{% endblock %}
{% block javascript %}
<script src="{% static 'js/home.js' %}"></script>
{% endblock %}
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.
My js :
$(".dump").on("click", function() {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
var a, today;
if (xhttp.readyState === 4 && 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();
});