0

Cannot serialize or save uploaded an image in APIview. If saving, a file is broken and cannot be open. If serialzing, getting: {"avatar":["No file was submitted."]} Request content:

MultiValueDict: {u'name': [<TemporaryUploadedFile: Avatar.jpg (image/jpeg)>]}

Settings:

FILE_UPLOAD_HANDLERS = [
'django.core.files.uploadhandler.TemporaryFileUploadHandler',
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')

URLs:

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)

Model:

class AvatarStorage(models.Model):
avatar = models.ImageField(verbose_name="Uploaded image", upload_to='media', null=True)

Serialzier:

class AvatarStorageSerializer(serializers.ModelSerializer):
avatar = serializers.ImageField(use_url=True)

class Meta:
    model = AvatarStorage

    fields = '__all__'

Views:

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)

For posting, i am using Postman, over there settings: Body=>Form-Data and choosing a file from disk.

If it's important, this is API for mobile

1
  • I think Avatar field specification is not neccessary in AvatarStorageSerializer. Commented Feb 6, 2018 at 7:17

2 Answers 2

2

Update the setting files FILE_UPLOAD_HANDLERS to like this

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

if you want to know more, read this

Sign up to request clarification or add additional context in comments.

3 Comments

It doesn't help, also I need to use TemporaryFileUploadHandler instead of MemoryFileUploadHandler as my imgs around 5-10 mb, and MemoryFileUploadHandler was designed for max 2.5mb
I already implemented this thing, now i uploaded 8mb image. The image saved without any loss.
Can you tell me exactly what is your problem
0

The problem was not in the code, I was missing required headers in Postman:

Content-Disposition: attachment; filename=upload.jpg;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.