Show a progress bar for downloading files using XHR2/AJAX

后端 未结 1 1754
一生所求
一生所求 2020-11-29 04:59

I am trying to download files using Ajax and show a custom download progress bar.

The problem is I can\'t understand how to do so. I wrote the code

1条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 05:22

    If you want to show the user a progress-bar of the downloading process - you must do the download within the xmlhttprequest. One of the problems here is that if your files are big - they will be saved in the memory of the browser before the browser will write them to the disk (when using the regular download files are being saved directly to the disk, which saves a lot of memory on big files).

    Another important thing to note - in order for the lengthComputable to be true - your server must send the Content-Length header with the size of the file.

    Here is the javascript code:

    
    
    Click to download

    And here is an example for the php code you can use:

    Note that I added a sleep to simulate a slow connection for testing on localhost.
    You should remove this on production :)

    0 讨论(0)
提交回复
热议问题