1

I use an <a> element to download a file in HTML page. It takes some seconds, so I want to show a loading by listening to the http response.

Is there a way to show loading when clicked <a> element, and close loading when download completed?

This is what I want:

<a href="https://..." download>download file</a>
wasanga7
  • 242
  • 1
  • 3
  • 17
eder
  • 73
  • 2
  • 8
  • I think you can look at [this](https://stackoverflow.com/a/2793756/4051471) – shrys Jun 12 '19 at 06:17
  • Possible duplicate of [Progress Bar (Download) Using HTML 5](https://stackoverflow.com/questions/9993192/progress-bar-download-using-html-5) – Justinas Jun 12 '19 at 07:06
  • @Justinas But i can't download a file by XMLHTTPRequest.I checked some solutions on stackoverflow.like: [download-file.js](https://gist.github.com/zynick/12bae6dbc76f6aacedf0). So,do i need to send a XMLHttprequest first, then use [createObjectURL](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL) to create a URL? – eder Jun 12 '19 at 07:54

2 Answers2

5

There are two ways :

  1. Use ajax for listening event or receive data from Back-end :
$(document).ready(function(){
  $("button").click(function(){
    $.ajax({url: "/getData", success: function(result){
      $("#div1").html(result);
    }});
  });
});
  1. In addition , you can use socket.io to listen event from Back-end .

At server send event :

socket.emit('sendData', 'Your Data');

At client listen event :

 socket.on('sendData', function(data) {
        console.log(data); // Your Data
      });
Le Quang
  • 515
  • 4
  • 10
1

XMLHttpRequest provides the ability to listen to various events that can occur while the request is being processed. Beneath those also is progress It checks if the amount of data that has been retrieved has changed.

var oReq = new XMLHttpRequest();

oReq.addEventListener("progress", updateProgress);

oReq.open("GET", url);

// progress on transfers from the server to the client (downloads)
function updateProgress (oEvent) {
  if (oEvent.lengthComputable) {
       // DO your Stuff here
  } else {
    // Unable to compute progress information since the total size is unknown
  }
}

Note: You need to add the event listeners before calling open() on the request. Otherwise the progress events will not fire.

DigitalJedi
  • 1,577
  • 1
  • 10
  • 29