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

前端 未结 4 708
北恋
北恋 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:41

    You can send pdf file as a response to any request without installing any packages.

    You can do the following.

    def get(request, *args, **kwargs):
        # some code
        # some code
    
        with fs.open("path/to/file/Report.pdf") as pdf:
            response = HttpResponse(pdf, content_type='application/pdf')
            filename = "Report.pdf"
            response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
    
            return response
    

    Now, open your postman and hit a get/post request.

    Important: Before clicking send button in postman, select the option send and download.

提交回复
热议问题