Home > Web Front-end > JS Tutorial > How Can I Reliably Detect File Download Completion in a Browser?

How Can I Reliably Detect File Download Completion in a Browser?

Linda Hamilton
Release: 2025-01-05 21:06:49
Original
474 people have browsed it

How Can I Reliably Detect File Download Completion in a Browser?

Handle File Download Completion Detection

Problem:

Detecting when a browser fully receives a dynamically generated file download becomes crucial when displaying waiting indicators. Currently, using an iframe's "load" event fails to address this issue due to browser inconsistencies.

Solution 1: Browser-Based Token Verification

A client-side JavaScript solution involves:

  • Generating a unique token for the download request.
  • Submitting the request with the token.
  • Displaying a "waiting" indicator.
  • Setting a timer to periodically check for a corresponding cookie with the token value.
  • Hiding the indicator upon finding the cookie.

On the server-side, the algorithm:

  • Checks for the token in the request.
  • Sets a cookie with the token value if found.

Code Snippet (JavaScript):

function setFormToken() {
  var downloadToken = new Date().getTime();
  document.getElementById("downloadToken").value = downloadToken;
  return downloadToken;
}
Copy after login

Code Snippet (PHP):

// Set a cookie to unblock submit button when download begins.
$TOKEN = "downloadToken";
$this->setCookieToken($TOKEN, $_GET[$TOKEN]);
Copy after login

Solution 2: Server Polling

Alternatively, a server-side approach involves:

  • Initiating file creation.
  • Polling the server until completion.
  • Downloading the ready file.

This method avoids creating temporary server files. However, it requires client-server communication during the waiting period.

Pros and Cons:

Using a browser token allows for dynamic detection, but may have browser compatibility issues. Server polling is a more reliable but slower option.

The above is the detailed content of How Can I Reliably Detect File Download Completion in a Browser?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template