Django Rest Framework文件上传
我正在使用Django Rest Framework和AngularJs上传文件。我的视图文件如下所示:
class ProductList(APIView): authentication_classes = (authentication.TokenAuthentication,)
def get(self,request):
if request.user.is_authenticated():
userCompanyId = request.user.get_profile().companyId
products = Product.objects.filter(company = userCompanyId)
serializer = ProductSerializer(products,many=True)
return Response(serializer.data)
def post(self,request):
serializer = ProductSerializer(data=request.DATA, files=request.FILES)
if serializer.is_valid():
serializer.save()
return Response(data=request.DATA)
由于post方法的最后一行应返回所有数据,因此我有几个问题:
- 如何检查里面是否有东西
request.FILES
? - 如何序列化文件字段?
- 我应该如何使用解析器?
回答:
使用FileUploadParser,一切都在请求中。改用put方法,你会在docs中找到一个示例:)
class FileUploadView(views.APIView): parser_classes = (FileUploadParser,)
def put(self, request, filename, format=None):
file_obj = request.FILES['file']
# do some stuff with uploaded file
return Response(status=204)
以上是 Django Rest Framework文件上传 的全部内容, 来源链接: utcz.com/qa/434173.html