In django rest framework, I am able to upload single file using danialfarid/ng-file-upload
views.py:
class PhotoViewSet(viewsets.ModelViewSet): serializer_class = PhotoSerializer parser_classes = (MultiPartParser, FormParser,) queryset=Photo.objects.all() def perform_create(self, serializer): serializer.save(blogs=Blogs.objects.latest('created_at'), image=self.request.data.get('image'))
serializers.py:
class PhotoSerializer(serializers.ModelSerializer): class Meta: model = Photo
models.py:
class Photo(models.Model): blogs = models.ForeignKey(Blogs, related_name='blogs_img') image = models.ImageField(upload_to=content_file_name)
When I try to upload multiple file. I get in
chrome developer tools: Request Payload
------WebKitFormBoundaryjOsYUxPLKB1N69Zn Content-Disposition: form-data; name="image[0]"; filename="datacable.jpg" Content-Type: image/jpeg ------WebKitFormBoundaryjOsYUxPLKB1N69Zn Content-Disposition: form-data; name="image[1]"; filename="datacable2.jpg" Content-Type: image/jpeg
Response:
{"image":["No file was submitted."]}
I don't know how to write serializer for uploading multiple file.
So you have two choices: let ModelViewSet and ModelSerializer handle the job and send the request using content-type=multipart/form-data; set the field in ModelSerializer as Base64ImageField (or) Base64FileField and tell your client to encode the file to Base64 and set the content-type=application/json.
I manage to solve this issue and I hope it will help community
serializers.py:
class FileListSerializer ( serializers.Serializer ) : image = serializers.ListField( child=serializers.FileField( max_length=100000, allow_empty_file=False, use_url=False ) ) def create(self, validated_data): blogs=Blogs.objects.latest('created_at') image=validated_data.pop('image') for img in image: photo=Photo.objects.create(image=img,blogs=blogs,**validated_data) return photo class PhotoSerializer(serializers.ModelSerializer): class Meta: model = Photo read_only_fields = ("blogs",)
views.py:
class PhotoViewSet(viewsets.ModelViewSet): serializer_class = FileListSerializer parser_classes = (MultiPartParser, FormParser,) queryset=Photo.objects.all()
I dont know it very well, but this is working... This is for my viewset.
def perform_create(self, serializer): obj = serializer.save() for f in self.request.data.getlist('files'): mf = MyFile.objects.create(file=f) obj.files.add(mf)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With