Django Rest Framework函数视图发布不起作用

时间:2018-07-13 18:22:16

标签: django python-3.x django-rest-framework django-views

因此,我正在尝试通过简单的Django Rest框架函数视图提供静态文件。它提供了200个代码,但没有下载文件。

这是代码:

@api_view(['POST'])
def download_file(request):

    if request.method == 'POST':
        serializer = MySerializer(data=request.data)
        filename = 'file.xlsx'
        file_full_path = "src/{0}".format(filename)

        with open(file_full_path, 'rb') as f:
            file = f.read()
        response = HttpResponse(file, content_type="application/xls")
        response['Content-Disposition'] = "attachment; filename={0}".format(filename)
        response['Content-Length'] = os.path.getsize(file_full_path)
        return response
    return Response(status=status.HTTP_400_BAD_REQUEST)

我在这里做什么错了?

1 个答案:

答案 0 :(得分:0)

您正在尝试使用 HTTP POST 方法下载文件,我认为这不是一个好方法。因此,请尝试 HTTP GET 进行下载。如果您希望提供其他参数(POST方法中的有效负载),则可以使用Query Parameter作为/api/end/point/?param=value1&param2=value2来实现。
因此,请尝试以下代码段,

@api_view(['GET'])
def download_file(request):
    if request.method == 'GET':
        filename = 'file.xlsx'
        file_full_path = "src/{0}".format(filename)

        with open(file_full_path, 'rb') as f:
            file = f.read()
        response = HttpResponse(file, content_type="application/xls")
        response['Content-Disposition'] = "attachment; filename={0}".format(filename)
        response['Content-Length'] = os.path.getsize(file_full_path)
        return response
    return Response(status=status.HTTP_400_BAD_REQUEST)