Reputation: 15
On client side i have some code
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)
and i want to create some post through api
on server side i have such code
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})
Where from .models
image = models.ImageField(upload_to='posts/', blank=True, null=True)
How can i built image from base64 string on server side ?
Upvotes: 0
Views: 586
Reputation: 764
Below code will give you an idea:
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)
hint: You pass data from the client-side and receive the data variable by the server-side and simply decode the base64 string to image and save in the directory...
Upvotes: 2