I am trying to create and download a file once a request has been sent. To send the request I use $.get . Below is the client-side & server-side code.
$(document).ready(function(){
$(".scrape").on("click", function(){
var url = $(".ib").val();
var req_obj = {};
req_obj["url"] = url;
$.get("/scraper", req_obj, function(data){
console.log(data);
var blob = new Blob([data]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "myFileName.txt";
link.click();
});
});
})
On Server I do
def scraper(request):
try:
url = request.GET.get('url')
html = urllib2.urlopen(url)
parsed_html = BeautifulSoup(html)
p_tags = parsed_html.findAll('p')
title = parsed_html.title.text
f = tempfile.NamedTemporaryFile()
for tag in p_tags:
f.write("\n")
f.write(tag.getText())
f.write("\n")
response = HttpResponse(f, content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename="%s.txt"' % title
except Exception as e:
res_dict = {"status":0,"Exception":e}
return HttpResponse(json.dumps(res_dict))
return response
The response code is 200 so everything is fine. Even in Content-Disposition header I can see the file. But an empty file(as response is empty) is being downloaded. How can I download the real file that is being created? Why I have to write client-side code for downloading in callback if I am saying application/force-download
?
Without ajax I also tried by passing the url as a query parameter. Still an empty txt file is being downloaded. Is the file is not being created at all?