简体   繁体   中英

how to export and then download a excel file with ajax call in background in php

I have to export large file in excel format and download it. i am using php excel. File is very large so it is taking much time in export . so i am using async ajax call and on server side, i am using session_write_close. Through this i can send concurrent calls.this is working fine if i stay on the same page... but when i send ajax call to export and download file and after that i redirect to a new page before the completion of that ajax call then that ajax call got cancelled and unable to download file. how can i export a file and then download it even after user has been redirected to a new URL.

There are several ways to perform download action on same page. Use of async may cause issues, your application may feel lagging between ajax operation.

As per my opinion you can do your ajax request in this way.

Upon creation of file use command-line approach if its possible. Or you can simply use system command with curl or elinks command and pass the url which is being used to generate the excel file.

curl http://mysite/generate/excel?id=123

or

elinks http://mysite/generate/excel?id=123

By using ajax ( sync ) you can make a request with keep alive option and check inside your code if file is created with some interval. your code will be like this

while (!file_exists("path/to/excel_file.xlsx")) {

   usleep(2000);
}

echo json_encode(["status" => true, "file_url" => "http://mysite/url/to/excel_file.xlsx"]);

Once you get response from ajax, On success function call below function with file url to download file through iframe on the same page.

downloadAttachment(response.file_url)

/* Amazing download management with error handling */

var downloadAttachment = function(link){

    var iframe = document.createElement("iframe"), iframeWindow;

    iframe.src = link;

    document.body.appendChild(iframe);

    iframe.onload = function(){

        response = JSON.parse($(iframe).contents().text())

        if(!response.status)
        {
            alert(response.message);
            $(iframe).remove();
        }
    }

    setTimeout(function(){

        $(iframe).remove();

    },10000)
}

This is logical flow of how to download big files if it is taking long time to generate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM