0

I am currently using Laravel Fast-Excel with the Chunks method: https://github.com/rap2hpoutre/fast-excel?tab=readme-ov-file#export-large-collections-with-chunk

I have the following in my controller:

public function download_excel(Request $request)
{
    return (new FastExcel(usersGenerator()))->download('file.xlsx');
}

public function usersGenerator() {
    foreach (User::cursor() as $user) {
        yield $user;
    }
}

In order to actually trigger the download from the browser, I have a button that opens the route in a new tab:

document.querySelector("#excel-download-button").addEventListener("click", function(event) {
    window.open('/excel-download', '_blank');
});

So the tab is opened for a split second, the download starts and the tab closes.

But I want to skip this behavior of using the new tab.

Is it possible to download it directly from a fetch request?

Something like this:

fetch('/excel-download')
  .then(response => {
    // ... download ...
  });

I couldn't find the way to do that

1 Answer 1

0

The idea is to create a hidden button with type download and click on it. In this case, a new window does not open.

function exportStep(request) {
        fetch(request, {
            method: "GET",
            cache: "no-store"
        }).then((response) => {
            return response.json()
        }).then((data) => {
            if (data.file && data.file.length) {
                let link = '/storage/export/' + data.file;
                let name = document.getElementById('courses').dataset.select;
                let downloadLink = document.createElement("a");
                downloadLink.href = link;
                downloadLink.download = name + " ({{date('d.m.Y')}}).xlsx";

                window.parent.document.getElementById('mainloader').classList.remove('show');

                document.body.appendChild(downloadLink);
                downloadLink.click();
                document.body.removeChild(downloadLink);

                exportButton.style.display = 'flex';
                exportProgress.style.display = 'none';
                progressTitle.innerText = '0%';
                progressShow.style.maxWidth = '0%';
            } else {
                if (data.step === 'export' || data.step === 'convert') {
                    progressTitle.innerText = data.percenttext;
                    progressShow.style.maxWidth = data.percent+'%';
                    exportStep(data.request);
                }
            }
        }).catch(function(error) {
            console.error("Request failed", error, ".")
        });
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.