Python 如何从base64创建文件对象以将其发送到Django

Python 如何从base64创建文件对象以将其发送到Django,python,django,django-rest-framework,Python,Django,Django Rest Framework,在客户端,我有一些代码 url = 'http://127.0.0.1:8000/api/create_post/' headers = {'Authorization': 'Token c63ee5854eb60618b8940829d2f64295d6201a96'} image_string = None with open("21485.jpg", "rb") as image_file: image_string = base64.b6

在客户端,我有一些代码

url = 'http://127.0.0.1:8000/api/create_post/'
headers = {'Authorization': 'Token c63ee5854eb60618b8940829d2f64295d6201a96'}
image_string = None

with open("21485.jpg", "rb") as image_file:
    image_string = base64.b64encode(image_file.read())

data ={ 'text':'new_post_python', 
        'image':image_string
    }

requests.post(url, json=data,headers=headers)
我想通过api创建一些帖子

在服务器端,我有这样的代码

class CreatePostView(APIView):
    permission_classes = (IsAuthenticated,) 
    def post(self,request,format=None):
        Post.objects.create(
            text=data.get('text'),
            author=request.user,
            image=...,
        )
        return Response({'created': True})
从哪里来,模特

image = models.ImageField(upload_to='posts/', blank=True, null=True)

如何从服务器端的base64字符串构建映像?

下面的代码将告诉您一个想法:

import base64
from PIL import Image
from io import BytesIO
path=PATH_OF_FILE
with open(path, "rb") as image_file:
    data = base64.b64encode(image_file.read())

im = Image.open(BytesIO(base64.b64decode(data)))
im.save(SAVE_AS)

提示:您从客户端传递数据,并通过服务器端接收数据变量,然后简单地将base64字符串解码为image并保存在目录中…

非常感谢,我已经这样做了,但在这之后,我的image的维度不同了。如何获得相同尺寸的图像?