首页 > 解决方案 > Django rest 框架:如何发送和下载 xlsx 文件?

问题描述

我一直在尝试使用 django-rest-framework 将文件发送到客户端。我可以将其作为字节发送,但我不知道如何在客户端管理它以将其下载为 xlsx 文件。我尝试的一切都以损坏的文件结束。

这是我到目前为止所拥有的:

# 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);

    });
}


标签: javascriptpythondjangodjango-rest-frameworkxlsx

解决方案


您可以使用 django 模型字段 models.FileField 轻松完成此操作,您可以按照本教程进行非常简短且易于理解的分步指南

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)

推荐阅读