0

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?

Coderaemon
  • 3,619
  • 6
  • 27
  • 50

2 Answers2

0

You're trying to load it via Ajax, which is unlikely to work. Instead, leverage your browser's own ability to download the file: just use window.location = url;

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • but I want to download as ajax only. Should I use some jquery plugin for this ? like : http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/ – Coderaemon Jul 27 '15 at 18:30
  • Or this won't work via Ajax at all ? How do I get the `url` in the client-side ? The response is empty ? – Coderaemon Jul 27 '15 at 18:37
  • @coderaemon Daniel is right, take a look at this post http://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax#7660817 – Shang Wang Jul 27 '15 at 20:51
0

Strangely changing the server side a little made it work. So I send a ajax request and get a file in response. Then store the response in a blog and download that file.

def scraper(request):
    try:
        url = request.GET.get('url')
        su_obj = ScrappedURL(url=url)
        su_obj.save()
        html = urllib2.urlopen(url)
        parsed_html = BeautifulSoup(html)
        p_tags = parsed_html.findAll('p')
        f = tempfile.NamedTemporaryFile()
        for tag in p_tags:
            f.write("\n")
            f.write(tag.getText())
            f.write("\n")
        f.seek(0)   
        response = HttpResponse(content_type ='application/force-download') 
        response['Content-Disposition'] = 'attachment; filename=file.txt'
        response.write(f.read())
    except Exception as e:
        res_dict = {"status":0,"Exception":e}
        return HttpResponse(json.dumps(res_dict))           
    return response

Have a look : http://scraper-bookwormapp.rhcloud.com/

Coderaemon
  • 3,619
  • 6
  • 27
  • 50