简体   繁体   中英

Django rest framework: How do I send and download xlsx file?

I have been stuck for awhile now trying to send a file to client side using django-rest-framework. I am able to send it as a byte but I don't know how to manage it client side to download it as an xlsx file. Everything I tried ends with a corrupted file.

Here is what I have so far:

# views.py
from django.http import HttpResponse
from openpyxl import load_workbook
from openpyxl.writer.excel import save_virtual_workbook

class DownloadApiView(APIView):
    authentication_classes = [BasicAuthentication, SessionAuthentication]
    permission_classes = (IsAuthenticated,)

    def post(self, request):
        try:
            file_path = './temp.xlsx'
            pk = request.data['xml_id']
            report = Report.objects.get(pk=pk)
            wbrd = load_workbook(filename=file_path)
            bytes = save_virtual_workbook(wb)

            response = HttpResponse(bytes, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            response['Content-Disposition'] = "attachment; filename=temp.xlsx"
            return response
        except Exception as error_msg:
            logger.error(error_msg)
            return Response({'error': 'Failed to retrieve file.'}, status=HTTP_400_BAD_REQUEST)

# client js called onclick()
function downloadFile(xmlID, type) {
    let url = '/api/download_report/';
    let $submit = $.ajax({
        type: 'POST',
        url: url,
        data: JSON.stringify(inputData),
        contentType: 'application/json',
        headers: {"X-CSRFToken": getCookie("csrftoken")},
    });
    $submit.done(function (data) {
        console.log(data);

        let a = window.document.createElement('a');
        a.href = window.URL.createObjectURL(new Blob(data, {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}));
        a.download = 'temp.xlsx';

        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);

    });
}


you can do this easily using django models field models.FileField you can follow this tutorial very brief and easy to understand step by step guide

https://blog.vivekshukla.xyz/uploading-file-using-api-django-rest-framework/

file = models.FileField(blank=False, null=False)
#you can edit this to 
file = models.FileField(upload_to='/the path where you want to download files',blank=False, null=False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM