Django rest框架:如何发送和下载xlsx文件?

时间:2020-02-17 13:33:53

标签: javascript python django django-rest-framework 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);

    });
}


1 个答案:

答案 0 :(得分:0)

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

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

file = models.FileField(空白= False,null = False) 您可以将其编辑为 file = models.FileField(upload_to ='/您要下载文件的路径',blank = False,null = False)