我正在使用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)
我使用的是同一堆栈,也在寻找文件上传的示例,但是由于我使用ModelViewSet而不是APIView,因此我的情况更简单。原来的钥匙是pre_save钩子。我最终将其与angular-file-upload模块一起使用,如下所示:
# Django class ExperimentViewSet(ModelViewSet): queryset = Experiment.objects.all() serializer_class = ExperimentSerializer def pre_save(self, obj): obj.samplesheet = self.request.FILES.get('file') class Experiment(Model): notes = TextField(blank=True) samplesheet = FileField(blank=True, default='') user = ForeignKey(User, related_name='experiments') class ExperimentSerializer(ModelSerializer): class Meta: model = Experiment fields = ('id', 'notes', 'samplesheet', 'user') // AngularJS controller('UploadExperimentCtrl', function($scope, $upload) { $scope.submit = function(files, exp) { $upload.upload({ url: '/api/experiments/' + exp.id + '/', method: 'PUT', data: {user: exp.user.id}, file: files[0] }); }; });