我是 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/