我需要从不同的对象存储桶下载图像对象,并通过 Django Rest Framework 将其发送给用户。
我有这样的东西:
if request.method == 'GET':
# Get object using swiftclient
conn = swiftclient.client.Connection(**credentials)
container, file = 'container_name', 'object_name'
_, data = conn.get_object(container, file)
# Send object to the browser
return Response(data, content_type="image/png")
data
变量包含字节类型。
测试时我收到错误:
'utf-8' 编解码器无法解码位置 0 中的字节 0x89:无效的起始字节
有什么办法可以解决这个问题?
最佳答案
如果您希望通过 Django Rest Framework 直接将图像传递给用户,使用 HttpResponse
可能更合适。
from django.http import HttpResponse
return HttpResponse(data, content_type="image/png")
Django Rest Framework 自己的 Response
将尝试呈现二进制数据,这可能会导致您看到的编码问题。
关于python - 通过 Django Rest 发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49447263/