0

无法在 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

4

2 回答 2

2

将设置文件 FILE_UPLOAD_HANDLERS 更新为这样

FILE_UPLOAD_HANDLERS=[
    'django.contrib.staticfiles.finders.MemoryFileUploadHandler',
    'django.contrib.staticfiles.finders.TemporaryFileUploadHandler',
]

如果您想了解更多信息,请阅读此内容

于 2018-02-05T05:16:10.273 回答
0

问题不在代码中,我在 Postman 中缺少必需的标头:

Content-Disposition: attachment; filename=upload.jpg;
于 2018-02-11T05:41:27.933 回答