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

2024-06-02 07:51:03 发布

您现在位置:Python中文网/ 问答频道 /正文

在客户端,我有一些代码

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字符串构建映像


1条回答
网友
1楼 · 发布于 2024-06-02 07:51:03

下面的代码将为您提供一个想法:

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并保存在目录中

相关问题 更多 >