首页 > 解决方案 > 从 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从未调用过。

我想念什么?

谢谢 !

标签: pythondjangopost

解决方案


正如@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>

它就像一个魅力!


推荐阅读