使用Django下载zip文件?

时间:2015-07-27 18:03:59

标签: python django download

我正在尝试在发送请求后创建并下载文件。要发送请求,我使用$ .get。以下是客户端&服务器端代码。

$(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();
        });
    });
})

在服务器上我做

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

响应代码是200,所以一切都很好。即使在Content-Disposition标题中,我也可以看到该文件。但是正在下载一个空文件(响应为空)。如何下载正在创建的真实文件?如果我说application/force-download,为什么我必须编写客户端代码以便在回调中下载?

没有ajax我也尝试将url作为查询参数传递。仍在下载空的txt文件。该文件根本没有创建吗?

2 个答案:

答案 0 :(得分:0)

你试图通过Ajax加载它,这不太可行。相反,利用浏览器自己的能力下载文件:只需使用window.location = url;

答案 1 :(得分: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/