Search code examples
javascriptpostdownload

How can I download a generated Excel file from a POST request?


I use this code to download a file generated by a AJAX POST request:

$.ajax({
        type: 'POST',
        url: url, 
        data: JSON.stringify(data),
        contentType: "application/json",
        success: (result) => {
            let blob = new Blob([result]);
            let link = document.createElement("a");
            link.href = window.URL.createObjectURL(blob);
            link.download = "inventory.xlsx";
            link.click();                
        }
    });

When I run that POST query using wget, I get a valid Excel file. However, when running above code, the resulting downloaded file is corrupt. Apperently 'something' happens in that JavaScript code, but what?

How can I download a generated Excel file from a POST request?

To give an idea of the differences, I did a diff using meld (right is javascript, left is wget):

enter image description here


Solution

  • To properly process the response given as a blob, inside the object you are passing to the $.ajax call, add the following property:

    xhrFields: {responseType: 'blob'}
    

    jQuery.ajax([ settings ])

    settings supports a property called xhrFields

    An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed.

    Those fields are expected to be passed to the native XMLHttpRequest object which has the responseType property to be set as 'blob'

    https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType

    responseType = 'blob'

    The response is a Blob object containing the binary data.