如何使用Django Rest Framework设置Content-Disposition标头

时间:2018-12-21 16:06:23

标签: django django-rest-framework

我正在使用Django REST框架提供图像。不幸的是,它下载而不是显示。我想我必须设置标题Content-Disposition = 'inline'。如何在ViewRenderer中做到这一点?

class ImageRenderer(renderers.BaseRenderer):
    media_type = 'image/*'
    format = '*'
    charset = None
    render_style = 'binary'

    def render(self, data, media_type=None, renderer_context=None):
        return data

class ImageView(APIView):
    renderer_classes = (ImageRenderer, )

    def get(self, request, format=None):
        image=MyImage.objects.get(id=1)
        image_file = image.thumbnail_png.file
        return Response(image)

1 个答案:

答案 0 :(得分:2)

根据Django文档中的this page,您可以通过以下方式设置Content-Disposition标头:

response = Response(my_data, content_type='image/jpeg')
response['Content-Disposition'] = 'attachment; filename="foo.jpeg"'