0

I am using Laravel Excel to Generate and download files. This is my code on the back end:

        $userExports = new UsersExport($filters);
        return $userExports->download();

I can download the file using postman but I am facing issues with jquery because I cannot make the browser start the download to the user.

This is my jquery code:

    url = Settings.AppSettings.Api + "users/export" + queryString;

    var settings = {
      "async": true,
      "url": url,
      "method": "GET",
      "headers": {
        "Authorization": "Bearer " + Session.AuthKey ,
        "cache-control": "no-cache",
      },
      "processData": false,
    }

    $.ajax(settings).done(function (response) {

        // I don't know what to code here.

    }).fail(function (response) {
        $(".Preloader").fadeOut();
        Materialize.toast(response.responseJSON.message, 3000);
        if (response.responseJSON.code == 401) {
            Session.Logout();
        }
    });

This is part of the response or file I am getting

PK �yOG�D�X�[Content_Types].xml��MN�0���"�%nY ��vAa �(0����ؖg�w{&i�@�nbE�{��y��d۸l m�����X�(���)���F��;@1_�����c)j�x/%��E��y� �QĿi!��K�y3�J<���Z1�0?Y�L%zV c��Ib7�����a/l٥P1:�q�r��j��j0A����u�""���(� ���W�M��)Tj�({ܲ�>�O��,X٭���>B��~׭���Ӥ6�J=�oBZ����t��X4���Cg�,���QgmrL�ٯc�e��t�� Z�?����hPv��±��u�j���R������}�Cv��PK �yO�78�K_rels/.rels���j�0��{ �{���1F�^ʠ�2��l�$���-}

juanmiguel431
  • 79
  • 2
  • 11

2 Answers2

0

This is what you need ,

$.ajax(settings).done(function (response) {
    var url = window.URL.createObjectURL(new Blob([response.data]));
    var link = document.createElement('a');
    var filename = "YourFileName.xls";
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();

})

Note : In your ajax setting add response data type as

dataType : 'blob',
Zar Ni Ko Ko
  • 352
  • 2
  • 7
0

Mainly, what it worked was add

"xhrFields":{ responseType: 'blob' },

I think the problem was that JQuery seems to have TEXT as a default response Type.

    url = Settings.AppSettings.Api + "users/export" + queryString;

    var settings = {
        "async": true,
        "url": url,
        "method": "GET",
        "headers": {
            "Authorization": "Bearer " + Session.AuthKey ,
            "cache-control": "no-cache",
        },
        "processData": false,
        "xhrFields":{
            responseType: 'blob'
        },
    }

    $.ajax(settings).done(function (data, textStatus, jqXHR) {

        var url = window.URL.createObjectURL(data);
        var link = document.createElement('a');
        var filename = "Usuarios.xlsx";
        link.href = url;
        link.setAttribute('download', filename);
        document.body.appendChild(link);
        link.click();

    });
juanmiguel431
  • 79
  • 2
  • 11