Saving a decoded temporary image to Django Imagefield

前端 未结 3 1827
天命终不由人
天命终不由人 2020-12-28 11:03

I\'m trying to save images which have been passed to me as Base64 encoded text into a Django Imagefield.

But it seems to not be saving correctly. The database repor

3条回答
  •  醉梦人生
    2020-12-28 11:17

    Another good approach based on this SO answer: https://stackoverflow.com/a/28036805/6143656 tried it and tested in django 1.10

    I made a function for decoded base64 file.

    def decode_base64_file(data):
    
        def get_file_extension(file_name, decoded_file):
            import imghdr
    
            extension = imghdr.what(file_name, decoded_file)
            extension = "jpg" if extension == "jpeg" else extension
    
            return extension
    
        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:
                TypeError('invalid_image')
    
            # Generate file name:
            file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.
            # Get the file name extension:
            file_extension = get_file_extension(file_name, decoded_file)
    
            complete_file_name = "%s.%s" % (file_name, file_extension, )
    
            return ContentFile(decoded_file, name=complete_file_name)
    

    Then you can call the function

    import decode_base64_file
    
    p = Post(content='My Picture', image=decode_based64_file(your_base64_file))
    p.save()
    

提交回复
热议问题