How to return generated file download with Django REST Framework?

后端 未结 5 1321
清歌不尽
清歌不尽 2021-02-04 03:20

I need to return generated file download as a Django REST Framework response. I tried the following:

def retrieve(self, request, *args, **kwargs):
    template =         


        
5条回答
  •  再見小時候
    2021-02-04 04:19

    I am using DRF and i found a view code to download file, which would be like

    from rest_framework import generics
    from django.http import HttpResponse
    from wsgiref.util import FileWrapper
    
    class FileDownloadListAPIView(generics.ListAPIView):
    
        def get(self, request, id, format=None):
            queryset = Example.objects.get(id=id)
            file_handle = queryset.file.path
            document = open(file_handle, 'rb')
            response = HttpResponse(FileWrapper(document), content_type='application/msword')
            response['Content-Disposition'] = 'attachment; filename="%s"' % queryset.file.name
            return response
    

    and url.py will be

    path('download//',FileDownloadListAPIView.as_view())
    

    I am using React.js in frontend and i get a response like

    handleDownload(id, filename) {
      fetch(`http://127.0.0.1:8000/example/download/${id}/`).then(
        response => {
          response.blob().then(blob => {
          let url = window.URL.createObjectURL(blob);
          let a = document.createElement("a");
          console.log(url);
          a.href = url;
          a.download = filename;
          a.click();
        });
      });
    }
    

    and after i got successful in downloading a file which also opens correctly and i hope this gonna work. Thanks

提交回复
热议问题