Скачать файл из POST-запроса - PullRequest
0 голосов
/ 14 февраля 2019

Я хотел бы загрузить файл, когда пользователь отправляет кнопку.Это 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 голосов
/ 14 февраля 2019

Как упомянул @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>

Работает как шарм!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...