V
V
Vladimir Kuts2018-10-12 08:23:53
JavaScript
Vladimir Kuts, 2018-10-12 08:23:53

django file transfer?

I need to upload a file from Django to a web page. The file is being transferred. But it does not open in Excel, and it is visually visible that the file encoding is different.
The greatly simplified code looks like this (we do not pay attention to the serializer and pk transmission - this does not affect the logic):
Server side:

class CEIViewset(GenericViewSet):
    queryset = CompetitionCEI.objects.all()
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = CompetitionCEISerializer

    @action(detail=False, methods=['POST'], permission_classes=(permissions.IsAuthenticated, ))
    def export_to_xls(self, request):
        ser = self.serializer_class(data=request.data)
        if ser.is_valid():
            pk = ser.validated_data.get('pk')

            with open(os.path.join(settings.BASE_DIR, 'data', 'sample.xls'), 'rb') as f:
                data = f.read()

            response = HttpResponse(data, content_type='application/xls; charset=utf-8')
            response['Content-Disposition'] = 'attachment; filename="sample.xls"'
            return response

Client side:
function exportXLS(pk) {
            $.ajax({
              method: 'POST',
              url: '/api/v1/cei/export_to_xls/',
              csrfmiddlewaretoken: '{{ csrf_token }}',
              contentType: 'application/json',
              responseType: 'blob',
              data: JSON.stringify({
                  pk: {{ object.pk }},
              }),
              success: function (response) {
              }
          }).done(function(response){
                  var newBlob = new Blob([response], {type: "application/xls"});
                  const data = window.URL.createObjectURL(newBlob);
                  var link = document.createElement('a');
                  link.href = data;
                  link.download="sample.xls";
                  link.click();
          })
  }

Original file
5bc02f7b3d387983821408.png
Downloadable file
5bc02fa084539906503386.png
It can be seen that the data is beating. Until I understand - on the client or server side? And how to fix it?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question