前后端分离下django 框架上传文件实现方式
实现方式一,通过model字段FileFiled()来实现
class Report(models.Model):
p_id = models.PositiveIntegerField('病人ID')
file = models.FileField(upload_to='uploads/report/%Y/%m/%d/')
def __str__(self):
return str(self.file)
class ReportSerializer(serializers.ModelSerializer):
file = serializers.FileField()
class Meta:
model = Report
fields = '__all__'
class ReportUploadView(generics.CreateAPIView):
# queryset = Report.objects.all()
serializer_class = ReportSerializer
parser_classes = [MultiPartParser, FormParser]
def post(self, request, *args, **kwargs):
print('Upload', request.data['p_id'])
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
serializer.save()
print(serializer.data)
serializer.data.pop('file')
# serializer.data['file'] = parse.unquote(serializer.data.pop('file'))
print('上传文件中', serializer.data)
return APIResponse(status.HTTP_201_CREATED, serializer.data)
else:
return APIResponse(status.HTTP_400_BAD_REQUEST, serializer.errors)