python - 从 POST 请求下载文件
问题描述
我想在用户提交按钮时下载文件。这是一个POST request
。我没有克服HttpResponse
在我的代码中返回。
这是我的观点:
class ExportDownloadView(View):
""" Create name authentification to download export file with expiration time """
template_name = 'export_download.html'
def get(self, request, **kwargs):
export_name = kwargs.pop('name', None)
ExportFile.objects.get(name__iexact=export_name)
if 'resp' in request.POST:
resp = self.downloadFile(export_name)
return resp
context = {
'name': export_name
}
return render(request, self.template_name, context)
def downloadFile(self, export_name):
fs = FileSystemStorage()
filename = export_name
if fs.exists(filename):
with fs.open(filename) as xls:
response = HttpResponse(xls, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=' + export_name
return response
else:
return HttpResponseNotFound(_('The requested xls file was not found in our server.'))
这是 HTML 文件:
<form action="" method="POST">
{% csrf_token %}
<input type="submit" class="btn btn-default" value="Download Export File : {{ name }}" name="resp" />
<a href="{% url 'home' %}" class="btn btn-default">{% trans 'Back' %}</a>
</form>
当用户点击提交按钮时,他应该能够下载链接的文件。但是,我不知道为什么if 'resp' in request.POST
从未调用过。
我想念什么?
谢谢 !
解决方案
正如@DanielRoseman 提到的,这是我的错误。我打电话给POST request
方法get()
!显然它不起作用!
在我看来 :
if 'resp' in request.GET:
resp = self.downloadFile(export_name)
return resp
在我的 HTML 模板中:
<form action="" method="GET">
<input type="submit" class="btn btn-default" value="Download Export File : {{ name }}" name="resp" />
<a href="{% url 'home' %}" class="btn btn-default">{% trans 'Back' %}</a>
</form>
它就像一个魅力!
推荐阅读
- rxjs - 在 RxJS 中何时使用 tap() 以及何时使用 map()
- c# - C# 有没有办法让我的 while 循环重新开始?
- javascript - 如何使用 jspdf-autotable 打印四个不同的表格
- html - 如何在本地创建的 HTML 代码中禁用父目录链接或限制对给定文件夹的访问?
- javascript - 将 API 调用的 Pdf 响应转换为 Blob 并生成 Blob Url
- operator-keyword - 无法理解 systemc '<<' 操作
- laravel - 错误:Laravel 中此集合实例上不存在属性 [kpi_description]
- postman - 邮递员 - 突出显示特定单元格
- c - 如何解释linux内核陷阱错误行?
- ruby-on-rails - 如何在 Rails 中显示索引翻译(rails-i18n)?