因此,我正在尝试通过简单的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)
我在这里做什么错了?
答案 0 :(得分:0)
您正在尝试使用 HTTP POST
方法下载文件,我认为这不是一个好方法。因此,请尝试 HTTP GET
进行下载。如果您希望提供其他参数(POST方法中的有效负载),则可以使用Query Parameter
作为/api/end/point/?param=value1¶m2=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)