简体   繁体   中英

How can client-side know that file is downloaded or received from server?

I have a file download request initiated from client-side for which I dynamically create a form element with some hidden attributes and submit (POST) to the server. Now while the request is in process, I need to show a loading/spinner which I need to hide, as soon as the download is complete (ie file received from server-side)

Currently, the mechanism I use is that a cookie name is generated from client-side and sent to the server in the request. When server is ready with the blob/file response, it sends the file to the client alongwith the same cookie. On the client side, it tries to read the cookie every few seconds and as soon as it finds the cookie, it hides the spinner.

My question is if there is any other way to achieve this ie not relying on cookie to determine file being ready.

Instead of making a hidden form element (which does not seem like the intended use for forms), use the jQuery $.post() method. You can then use callbacks to determine when the file has finished downloading, as well as catch and deal with any errors that may occur.

For example in your download request handler:

$.post("/some-url", data)
  .done(function(responseData) {
    // do something with data
  })
  .fail(function(request, statusText, error) {
    // handle error
  })
  .always(function() {
    // hide spinner
  });

// show spinner

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