本文介绍了Django Rest框架文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Django Rest Framework 和 AngularJs 上传文件.我的视图文件如下所示:
I am using Django Rest Framework and AngularJs to upload a file. My view file looks like this:
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方法的最后一行应该返回所有数据,我有几个问题:
As the last line of post method should return all the data, I have several questions:
- 如何检查
request.FILES
中是否有内容? - 如何序列化文件字段?
- 我应该如何使用解析器?
推荐答案
使用 FileUploadParser,这一切都在请求中.改用 put 方法,您会在文档中找到示例 :)
Use the FileUploadParser, it's all in the request.Use a put method instead, you'll find an example in the 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框架文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!