python - 如何从 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 字符串构建图像?
解决方案
下面的代码会给你一个想法:
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字符串解码为图像并保存在目录中......
推荐阅读
- python-3.x - 在 python 3 中传递一个字符串变量作为函数参数并在函数中调用它
- coldfusion - 使用 CFWHEELS 在模型中添加自定义方法
- javascript - 如何将媒体从 text/plain 更改为 application/json?
- wso2 - 端点[状态:暂停]
- c# - XML 未正确序列化为对象
- html - 屏幕尺寸过小时文本重叠
- kendo-ui - Kendo Window - 使用自定义更新
- react-native - store.dispatch 不是一个函数 - 将原生 redux-persist 与 redux-thunk middlware 反应
- php - 添加 if user is guest/customer 语句到 PHP
- amazon-web-services - 适用于 Amazon Redshift 的 JDBC 驱动程序与 Python 适配器之间的区别