How to display and remove a loading .gif when downloading a file?

后端 未结 4 878
孤城傲影
孤城傲影 2021-01-20 01:20

I have a button that, when clicked on, needs to download a file by submitting a form using POST. [Edit to clarify: The file being downloaded is dynamically

相关标签:
4条回答
  • 2021-01-20 01:46

    I've posted an answer in this question that demonstrates how to do this. See the demo at http://tomsfreelance.com/stackoverflow/imageDownloadLoading/main.php and source files at http://tomsfreelance.com/stackoverflow/imageDownloadLoading/

    0 讨论(0)
  • 2021-01-20 01:59

    I've done this with 2 librairies Under MIT licence : BinaryTransport and FileSaver. In this exemple, i'm downloading an Excel file generated server side.

    HTML (in head tag):

    <script src="/E1/js/jquery.binarytransport.js" charset="UTF-8"></script>
    <script src="/E1/js/FileSaver.js" charset="UTF-8"></script>
    

    Javascript :

    function ExportToExcel(urlExcel, fileName){
          $("body").css("cursor", "progress");
          $.ajax({
              url: urlExcel,
              type: "GET",
              dataType: 'binary',
              headers:{'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','X-Requested-With':'XMLHttpRequest'},
              processData: false,
              success: function(blob){
                    $("body").css("cursor", "default");
                    saveAs(blob, fileName);
              },
                error : function(result, status, error){
                    $("body").css("cursor", "default");
              } 
            });  
    }
    

    For a custom loading animation, just call it where I change cursor type at these lines :

    $("body").css("cursor", "progress");
    $("body").css("cursor", "default");
    
    0 讨论(0)
  • 2021-01-20 02:02

    When you submit the form the whole page is going to refresh, the loading image will definitely be removed unless you are not adding it somewhere else on page load.

    0 讨论(0)
  • 2021-01-20 02:05

    You should either serve a URL to the .gif or stream it encoded as Base64

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