python - 无法在django中下载文件

标签 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

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

========== 补充: 为了让您全面了解 View 文件,下载是通过索引调用的,仅此而已:

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))

最佳答案

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

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))

关于python - 无法在django中下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49501849/

相关文章:

python - 获取要展开的 WxPython 面板项

android - 使用 picasso 加载时图像未保存到存储中

Django:Case 有条件

python - 如果我在 Python 3 中将文件截断为零,我是否还需要寻找零位置?

python - Plotly:躲避散点图分类轴上的重叠点

python - Pyramid 记录

perl - 我如何检查我是否在 Perl 中下载了整个文件?

python - Django auth + MySQL 迁移,行大小太大

php - 如何使用php从数据库/文件夹下载文件

r - R Shiny-将csv下载到工作目录