1

I am using the following js script to post variables from a web form to a python script which then generates a docx documents and in turn responds back to the ajax POST to download it, I can successfully get a file however it seems corrupt when trying to open with word(possibly due to mis-encoding), the size of the file is around 300K, but when downloaded the size is 500K

The reason I would like to use the ajax script is so that I can get a full handle of the situation, sometimes the server side python script returns an error and I would like to use ajax to display this to the user to understand what is going on.

How can I modify the js script to properly save the docx file. I have tried different dataType for the ajax post, but I get parse error when using anything but text type.

Code:

var url = $('#myform').attr('action');

var data = $('#myform').serialize();

$.ajax({
    type: "post",
    url: url,
    data: data,
    dataType: 'text',
    success: function(responseData,textStatus, xhr)
    {
        console.log('got response' + textStatus + xhr.getResponseHeader("Content-Disposition"));
        var blob=new Blob([responseData],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"});
        var link=document.createElement('a');
        link.href=window.URL.createObjectURL(blob);
        link.download="test.docx";
        link.click();
    },
    error: function (jqXHR, exception) 
    {
         var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        console.log(msg);
    } 

})
Ossama
  • 2,401
  • 7
  • 46
  • 83
  • [Similar](https://stackoverflow.com/questions/17657184/using-jquerys-ajax-method-to-retrieve-images-as-a-blob) – Musa Mar 01 '18 at 02:36

1 Answers1

0

This seems to be a somewhat known issue with jQuery, it can corrupt binary files, because of an intermediate conversion to string.

Nevertheless, check the solutions that are provided here. If that does not suite your needs then you may want to use this fix.

Mario Z
  • 4,328
  • 2
  • 24
  • 38