Itriedit
Itriedit

Reputation: 79

how to write File Download with django Rest framework?

I have a model with filefield with xls and xlsx and person who uploaded it i need to write api view in DRF that returns download on front end how can my view be?

models.py

class FileuploaderView(BaseModel):
    file = models.FileField(
        upload_to='',
        validators=[FileExtensionValidator(['xls', 'xlsx'])],
    )
    created_by = models.ForeignKey(
        'other model',
        related_name= '',
        null=True,
        on_delete=models.SET_NULL,
    )

views.py:

def DownloadView(APIView):
        def get(self, request, id, format=None):
            queryset = Model.objects.get(id=id)
            file_handle = queryset.file.path
            document = open(file_handle, 'rb')
            response = HttpResponse(FileWrapper(document), content_type='')
            response['Content-Disposition'] = 'attachment; filename="%s"' % queryset.file.name
            return response

Is it the

Upvotes: 1

Views: 4727

Answers (1)

Nandan
Nandan

Reputation: 422

You might want this:

file_path = file_url
FileData = open(file_path,"r")
response = HttpResponse(FileData,content_type='application/msword')
response['Content-Disposition'] = 'attachment; filename=NameOfFile'
return response

also checkout this

Upvotes: 2

Related Questions