如何在Django REST Framework中解析multipart form-data中的多文件?
Hey there, I’ve run into this exact issue before—let’s break down what’s happening and how to fix it.
The root problem here is how Django’s QueryDict (the type of request.data when using form/multipart parsers) handles multiple values for the same key. When you use request.data['image'], it defaults to returning only the last value in the list, which is why you’re only seeing the second image.
Quick Fix: Use getlist() to Retrieve All Files
Instead of accessing the key directly, use the getlist() method built into QueryDict. This will return all your uploaded files as a proper list of TemporaryUploadedFile objects:
# Get all uploaded images as a list images = request.data.getlist('image') # Now you can iterate through each file normally for image in images: print(f"Processing file: {image.name} (type: {image.content_type})") # Add your file processing logic here (save to model, resize, etc.)
Handling Multiple Files in Your Serializer
If you’re using a ModelSerializer to save these files to your database, you’ll need to adjust it to accept multiple entries. Here’s a simple example:
1. Update Your Serializer to Support Lists
from rest_framework import serializers from .models import YourImageModel # Base serializer for a single image class SingleImageSerializer(serializers.ModelSerializer): class Meta: model = YourImageModel fields = ('image',) # List serializer to handle multiple images class MultipleImageSerializer(serializers.ListSerializer): def create(self, validated_data): # Bulk create all images at once return YourImageModel.objects.bulk_create( [YourImageModel(**item) for item in validated_data] ) # Attach the list serializer to your main serializer class YourImageModelSerializer(serializers.ModelSerializer): class Meta: model = YourImageModel fields = ('image',) list_serializer_class = MultipleImageSerializer
2. Use the Serializer in Your View
In your ModelViewSet, override the create method to handle the list of files:
from rest_framework import viewsets from .serializers import YourImageModelSerializer class ImageViewSet(viewsets.ModelViewSet): serializer_class = YourImageModelSerializer parser_classes = (MultiPartParser, FormParser) def create(self, request, *args, **kwargs): # Pass the list of images to the serializer with many=True serializer = self.get_serializer(data=request.data.getlist('image'), many=True) serializer.is_valid(raise_exception=True) self.perform_create(serializer) return Response(serializer.data, status=status.HTTP_201_CREATED)
A Quick Note on Frontend Submission
Make sure your frontend is sending all files with the same key name (image in your case). Some frameworks might append [] to the key (like image[])—if that’s happening, adjust your getlist() call to match:
images = request.data.getlist('image[]')
内容的提问来源于stack exchange,提问作者svalemento

