无法在django中下载文件

时间:2018-03-26 22:49:58

标签: python django download frontend backend

我是django的新手,我开发了一个django网站,允许人们通过输入书名来下载epub文件。我已经检查了关于下载的django api,代码似乎工作正常(没有报告错误),但我的浏览器没有弹出下载窗口。我正在测试127.0.0.1:8000,这是我的代码的一部分

view.py

def download(request, file_path, book_name):
    if os.path.exists(file_path):
        response = HttpResponse(content_type="application/epub+zip")
        response['X-Sendfile'] = file_path
        response['Content-Disposition'] = 'attachment; filename=abc.epub'
        print (response)
        return response
    raise False

根据我的控制台,它可以找到文件路径,并打印显示的消息

<HttpResponse status_code=200, "application/epub+zip">
[26/Mar/2018 18:31:03] "POST / HTTP/1.1" 200 509

一切似乎都运行正常,只是下载窗口没有弹出。有谁知道哪里出错了?谢谢!

========== 补充: 为了让您全面了解视图文件,可以通过索引调用下载,全部是:

def index(request):
    template = loader.get_template('index.html')
    book_name = ''
    result = ''
    if request.method == "POST": # check if user actually type a book name
        book_name = request.POST.get("book_name")
    cwd = os.getcwd()
    if book_name != '': # search and create are functions from other file which would create an epub file and put it in current directory
        result = search.search_ask(book_name)
        create.create(book_name)

        file_path = os.path.join(cwd, book_name) + '.epub'
        download(request, file_path, book_name)

    context = {'return_value': book_name,
               'result_1': result,
               'cwd': cwd}

    return HttpResponse(template.render(context, request))

1 个答案:

答案 0 :(得分:1)

您不会返回下载方法返回的响应对象。最多的是:

return donwload(request, file_path, book_name)

download_response = donwload(request, file_path, book_name)
if download_response:
    return download_response
else:
    # not found or other return.
代码中的

始终返回

return HttpResponse(template.render(context, request))