无法在 APIview 中序列化或保存上传的图像。如果保存,文件已损坏且无法打开。如果序列化,获取: {"avatar":["No file was submit."]} 请求内容:
MultiValueDict: {u'name': [<TemporaryUploadedFile: Avatar.jpg (image/jpeg)>]}
设置:
FILE_UPLOAD_HANDLERS = [
'django.core.files.uploadhandler.TemporaryFileUploadHandler',
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
网址:
urlpatterns = [
url(r'^test/$', TestReturn.as_view(), name='test-detail'),
url(r'^users/$', UserProfileAll.as_view(), name='userprofile-detail'),
url(r'^avatar/', UploadAvatar.as_view(), name='images')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
模型:
class AvatarStorage(models.Model):
avatar = models.ImageField(verbose_name="Uploaded image", upload_to='media', null=True)
串行器:
class AvatarStorageSerializer(serializers.ModelSerializer):
avatar = serializers.ImageField(use_url=True)
class Meta:
model = AvatarStorage
fields = '__all__'
意见:
class UploadAvatar(APIView):
parser_classes = (MultiPartParser,)
def post(self, request, format=None):
serializer = AvatarStorageSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
对于发布,我使用 Postman,在那里设置:Body=>Form-Data 并从磁盘中选择一个文件。
如果它很重要,这是移动 API