首页 > 解决方案 > 如何从 base64 创建 FIle 对象以将其发送给 Django

问题描述

在客户端我有一些代码

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})

来自 .models

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

如何在服务器端从 base64 字符串构建图像?

标签: pythondjangodjango-rest-framework

解决方案


下面的代码会给你一个想法:

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字符串解码为图像并保存在目录中......


推荐阅读