How do I use django rest framework to send a file in response?

前端 未结 4 696
北恋
北恋 2021-02-15 18:27

I need to send a pdf file and some other parameters in response to a get API call using django rest framework.

How can I do it? I tried this but it gives an error

4条回答
  •  抹茶落季
    2021-02-15 18:40

    If you really need to serve binary files directly from your backend (e.g. when they're being generated dynamically) you can use a custom renderer:

    from rest_framework.renderers import BaseRenderer
    
    class BinaryFileRenderer(BaseRenderer):
        media_type = 'application/octet-stream'
        format = None
        charset = None
        render_style = 'binary'
    
        def render(self, data, media_type=None, renderer_context=None):
            return data
    

    Then use it in your action in a viewset:

    @detail_route(methods=['get'], renderer_classes=(BinaryFileRenderer,))
    def download(self, request, *args, **kwargs):
        with open('/path/to/file.pdf', 'rb') as report:
            return Response(
                report.read(),
                headers={'Content-Disposition': 'attachment; filename="file.pdf"'},
                content_type='application/pdf')
    

提交回复
热议问题