from rest_framework import routers, serializers, viewsets import base64 from .models import upload import zipfile import os
class Base64ImageField(serializers.ImageField): """ A Django REST framework field for handling image-uploads through raw post data. It uses base64 for encoding and decoding the contents of the file. Heavily based on https://github.com/tomchristie/django-rest-framework/pull/1268 Updated for Django REST framework 3. """ def to_internal_value(self, data): from django.core.files.base import ContentFile import base64 import six import uuid # Check if this is a base64 string if isinstance(data, six.string_types): # Check if the base64 string is in the "data:" format if 'data:' in data and ';base64,' in data: # Break out the header from the base64 content header, data = data.split(';base64,') # Try to decode the file. Return validation error if it fails. try: decoded_file = base64.b64decode(data) except TypeError: self.fail('invalid_image') # Generate file name: file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough. # Get the file name extension: file_extension = self .get_file_extension(file_name, decoded_file) complete_file_name = "%s.%s" % (file_name, file_extension, ) data = ContentFile(decoded_file, name=complete_file_name) return super(Base64ImageField, self).to_internal_value(data) def get_file_extension(self, file_name, decoded_file): import imghdr extension = imghdr.what(file_name, decoded_file) extension = "zip" if extension == "jpeg" else extension #<--error line---> i am converting Base 64 data into zip file #examplezip.write(serializers.ImageField,compress_type = zipfile.ZIP_DEFLATED) #examplezip.close() return extension class uploadSerializers(serializers.ModelSerializer): image=Base64ImageField( max_length=None, use_url=True, ) #image = serializers.ImageField(max_length=None,use_url=True) class Meta: model = upload fields = ('id','image','user') extra_kwargs = {'user': {'required': False}} On Thursday, April 30, 2020 at 2:05:25 PM UTC+5:30, yashwanth balanagu wrote: > > {"image":["File extension “zip” is not allowed. Allowed extensions are: > bmp, dib, gif, tif, tiff, jfif, jpe, jpg, jpeg, pbm, pgm, ppm, pnm, png, > apng, blp, bufr, cur, pcx, dcx, dds, ps, eps, fit, fits, fli, flc, ftc, > ftu, gbr, grib, h5, hdf, jp2, j2k, jpc, jpf, jpx, j2c, icns, ico, im, iim, > mpg, mpeg, mpo, msp, palm, pcd, pdf, pxr, psd, bw, rgb, rgba, sgi, ras, > tga, icb, vda, vst, webp, wmf, emf, xbm, xpm."]} > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f64709cf-3452-4658-9903-599c75e247c9%40googlegroups.com.