Django的休息框架文件上传 [英] Django Rest Framework File Upload

查看:365
本文介绍了Django的休息框架文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Django的REST框架和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方法的最后一行应该返回所有的数据,我应该怎么写那里,或者如何检查是否有没有在request.FILES什么,以及如何的FileField序列器或者我应该如何使用分析器?请帮助..

As the last line of post method should return all the data , what should I write there , or how to check there if there is anything in request.FILES , and how to serializer filefield or how should I use Parser? please help..

推荐答案

使用 FileUploadParser ,它的所有请求。
使用看跌方法来代替,你会在文档找到一个示例:)

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的休息框架文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆