将base64图像数据上传并保存到django rest framework

时间:2018-04-07 23:04:36

标签: python django django-rest-framework base64

我在将base64图像数据保存到django图像字段时遇到问题,这是我尝试过的:

所以基本上我使用axios POST请求从前端接收base64图像数据。然后在我的django rest framework api View中处理图像数据。

我尝试了两种变体:

1)将解码后的base64写入TemporaryFile,然后将其传递给imageField

2)使用TemporaryFile打开PIL.Image.open(img_temp),然后将PIL.Image转换为InMemoryUploadedFile并将其传递给imageField

但是在这两种情况下我都会收到错误:image : ["Upload a valid image. The file you uploaded was either not an image or a corrupted image."]

我不太清楚为什么会出现这个错误,因为当我使用img.show()时,图片显示得很好。

Django休息框架

        base64_data = request.data['image_data'][22:]
        decode_image = base64.b64decode(base64_data)
        img_temp = TemporaryFile()
        img_temp.write(decode_image)
        img_temp.flush()

        img = PIL.Image.open(img_temp)
        img_format = '.' + img.format
        img.show()

        image_io = BytesIO()
        img.save(image_io, format=img.format)
        file = InMemoryUploadedFile (
            image_io,
            None,
            'photo' + img_format,
            'image/' + img.format,
            sys.getsizeof(image_io),
            None,
        )
        img.close()

        data = {
            'image': File(img_temp) # I have tried passing File(img_tem) and "file" into the image field
        }

        serializer = ListSerializer(data=data, context={'request': request})
        if serializer.is_valid():
            instance = serializer.save()
            instance.save()

1 个答案:

答案 0 :(得分:0)

更新:想通了

        base64_data = request.data['image_data'][22:]
        decode_image = base64.b64decode(base64_data)

        img = PIL.Image.open(BytesIO(decode_image))
        img_format = '.' + img.format
        img.show()

        fileData = BytesIO(decode_image)
        file = InMemoryUploadedFile ( # arguments: 'file', 'field_name', 'name', 'content_type', 'size', and 'charset'
            fileData,
            None,
            'photo' + img_format,
            'image',
            len(decode_image),
            None,
        )
        img.close()

        data = {
            'image': file
        }

        serializer = ListSerializer(data=data, context={'request': request})
        if serializer.is_valid():
            instance = serializer.save()
            instance.save()