Django休息框架:如何下载图像与此图像直接发送到正文 [英] Django rest framework : How to download image with this image send directly in the body
问题描述
我需要直接在body请求中返回一个图像,但是我收到一个生成的文件,没有扩展名,空的数组/ json里面...
I need to return an Image directly in the body request, but i get in response a generated file with no extension and an empty array/json inside...
我使用python 3,Django == 1.10.5和djangorestframework == 3.5.3
I'm using python 3, Django==1.10.5 and djangorestframework==3.5.3
我的models.py
My models.py
class Image(models.Model):
class Meta:
verbose_name = _('Image')
verbose_name_plural = _('Images')
creation_date = models.DateTimeField(
help_text=_('Creation date'),
auto_now_add=True,
editable=False
)
modified_date = models.DateTimeField(
help_text=_('Last modification date'),
auto_now=True
)
image_file = models.ImageField(upload_to='', null=True)
我的serializers.py
My serializers.py
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = ('image_file',)
我的views.py
My views.py
class ImageViewSet(NestedViewSetMixin, viewsets.ModelViewSet):
http_method_names = ['get', 'put']
queryset = Image.objects.all()
serializer_class = ImageSerializer
pagination_class = None
def get_queryset(self, *args, **kwargs):
image = Image.objects.last()
filename = image.image_file
size = filename.size
response = FileResponse(open(filename.path, 'rb'), content_type="image/png")
response['Content-Length'] = size
response['Content-Disposition'] = "attachment; filename=%s" % 'notification-icon.png'
return response
如果有人找到我做错了,我会真的很感激。
Thx很多; p
If someone find what I'm doing wrong, I will really appreciate. Thx a lot ;p
编辑:我已经尝试过django.core.files.File ,filewrapper,并尝试去杀死序列化器,无效。
Edit : i have tryed with django.core.files.File, filewrapper and tryed to desactivate the serializer without effect.
推荐答案
您可以使用 base64
模块将图像文件编码为base64格式(原始字符串),然后分配给一个字段以传输图像。
You can use base64
module to encode the image file to base64 format (a raw string), and then assigned it to a field to transfer your image.
我已更新您的 ImageSerializer
包含一个名为 base64_image
的新文件,该文件是从base64格式的模型图像文件编码的。
I have updated your ImageSerializer
to include a new filed named base64_image
which is encoded from the model's image file with base64 format.
以下示例供您参考:
from django.core.files import File
import base64
class ImageSerializer(serializers.ModelSerializer):
base64_image = serializers.SerializerMethodField()
class Meta:
model = Image
fields = ('base64_image', 'id')
def get_base64_image(self, obj):
f = open(obj.image_file.path, 'rb')
image = File(f)
data = base64.b64encode(image.read())
f.close()
return data
views.py
views.py
class ImageViewSet(viewsets.ModelViewSet):
http_method_names = ['get', 'put']
queryset = Image.objects.all()
serializer_class = ImageSerializer
pagination_class = None
urls.py
urls.py
from rest_framework.routers import DefaultRouter
# Register viewset
router = DefaultRouter()
router.register(r'image', ImageViewSet)
urlpatterns += router.urls
最后,您可以使用url打开浏览器: http:// l ocalhost:8000 / image /
,您将收到以下回复:
Finally, you can open a browser with url: http://localhost:8000/image/
, and you will get the response like that:
[
{
"base64_image": "iVBORw0KGg.....",
"id": 1
}
]
如何在前端或应用程序中显示您的图像?
当您的前端得到上面的json,你需要将base64格式转换成图像原始数据。
How to show your image in front-end or app?
When your front-end get the json above, you need to convert the base64 format back to image raw data.
document.getElementById('img').setAttribute( 'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEU.......');
如何将Base64字符串转换为BitMap图像在ImageView中显示?
我已经上传了一个例子到 GitHub 。希望会有所帮助。
I have upload an example to GitHub. Hope it would help.
这篇关于Django休息框架:如何下载图像与此图像直接发送到正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!