前后端分离下django 框架上传文件实现方式
实现方式一,通过model字段FileFiled()来实现
model类
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)
serializer 类
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)
来自为知笔记(Wiz)
标签:__,文件,data,self,django,file,上传,class,serializer From: https://www.cnblogs.com/baiyifengyun/p/17645669.html