从POST请求下载文件

时间:2019-02-14 15:54:30

标签: python django 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

我想念什么吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

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

它就像一种魅力!