Can I redirect to a page after a download? Using the following code to download a file:
public function download_file(Request $request)
{
return Storage::disk('s3')->download($request->file_path);
}
The download_file method is being called from the front end with JavaScript using
window.location.href = url_to_download_file_method;
I want to redirect to another page after the download is triggered. Is it possible?
No and yes. You would need to handle the download in Javascript and then redirect in Javascript as well. But downloads with js is tricky
@sinnbeck So right now I'm basically in a loop:
The page calls my controller download method using location.href and the controller returns a download trigger which means none of these 2 can redirect.
Is there a simple way to change the logic so that my page will trigger Storage::disk('s3')->download($request->file_path); and make it redirect as well? (Doesn't have to be JavaScript)
If you are using Javascript, you can open a tab for the download and then redirect the user in the current window.
window.open(url_to_download_file_method, '_blank'); // Opens a new tab
// Redirect the user
// ...
@MohamedTammam I tried that, but the problem is that the browsers today recognize it as a pop up and block it :/
@cooperino Use that trick.
let a = document.createElement('a');
a.href = url_to_download_file_method;
a.target = '_blank';
a.click();
@MohamedTammam Apparently it's also now considered as a pop up and is blocked :D
@cooperino Try to add first in the page.
let a = document.createElement('a');
a.href = url_to_download_file_method;
a.target = '_blank';
document.body.appendChild(a);
setTimeout(() => {
a.click();
document.body.removeChild(a);
}, 500);
@MohamedTammam I found another solution, using JS fetch API (from SO):
fetch(downloadUrl)
.then(resp => resp.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
window.location = redirectUrl; //redirect
})
.catch(() => alert('error));
@cooperino I recently resorted to using Livewire for this.
Please sign in or create an account to participate in this conversation.