简体   繁体   English

Django rest 框架返回 base64 图像 URL 编码

[英]Django rest framework returning base64 image URL encoded

I have my viewset that returns a basse64 encoded image in the image variable:我的视图集在image变量中返回一个 basse64 编码图像:

with open(f"image_file.jpg" , "rb") as image_file:
            order.image = base64.encodebytes(image_file.read()).decode('utf-8')

The thing is, if this code is executed locally like python script.py it returns the right base64 and I can display it, but this viewset is returning a base64 that's URL encoded.问题是,如果此代码像python script.py一样在本地执行,它会返回正确的 base64 并且我可以显示它,但是此视图集返回的是 base64,它是 URL 编码的。 Instead of returning something like NMR//9k= , it's returning NMR/9k%3D%0A .它没有返回NMR//9k=之类的东西,而是返回NMR/9k%3D%0A

How can I change this?我怎样才能改变这个? I need the proper base64 encoding to display the image on the front.我需要正确的 base64 编码才能在正面显示图像。

I managed to solve this issue by creating a dict for the base64 images outside the serializer of the model, which was the one doing that URL encoding.我设法通过在 model 的序列化程序之外为 base64 图像创建一个 dict 来解决这个问题,这是执行 URL 编码的序列化程序。 I also had to remove new line characters as the response was drawing them as characters.我还必须删除换行符,因为响应将它们绘制为字符。

with open(f"image_file.jpg" , "rb") as image_file:
    images_dict["image_1"] = base64.encodebytes(image_file.read()).decode('utf-8').replace("\n", "")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM