How to save base64 string as an image to local server in django python

  django, image, python

I have base64 string and I try to encode it and then save it in a folder. So far I have been doing this

data = {"status":"Trial"}
if request.method == 'POST':
        decoded = request.body.decode("UTF-8")
        userdata = json.loads(decoded)
        image = base64.b64decode(str(userdata))
        print(type(image))

        save_path = "Dummy/test"
        if not os.path.exists(save_path):
            pathlib.Path(save_path).mkdir(parents=True, exist_ok=True)
            img_save_path = "%s/%s%s" % (save_path, str(uuid.uuid4()), ".jpeg")
            with open(img_save_path, "wb+") as f:
                for chunk in image.chunks():
                    f.write(chunk)
return JsonResponse(data)

when I try the above code, the image is saved inside Dummy/test directory but when I open the image.. it says that the image can not be opened. Is there a right way to save base64 string as an Image in django python?

Source: Python Questions

LEAVE A COMMENT