How to operate a gif loading when using the window.location.href when downloading a document?

3

I have the following click event, which when exporting a pdf, is downloaded, but I wanted to place a gif animation loading while it is generated. I've tried to do it like this:

 $("#export_pdf").click(function (e) {
        e.preventDefault();
        $("#ajax_loader").css("display", "");
        var formato = "PDF";
        var url = "/Obras/Export?format=" + formato + "&nombreObra=" + $('#nombre_obra').val();
        window.location.href = url;
        $("#ajax_loader").hide();
    });

But it is not enough to show the image of the div by loading ajax_loader. I'm exporting a PDF document , using MVC C # and jquery, so I do not use ajax, so I use window.location.href.

I tried to do it, but it does not work for me. If anyone has any ideas, I would appreciate it a lot.

    
asked by Danilo 02.07.2018 в 23:49
source

1 answer

1

Much depends on the instantaneity of that generation. You could generate the download link dynamically and after a second click programmatically, when you hide the "loading".

In chrome it will not work because the download attribute is ignored, but the following could work in Firefox since you request the PDF to the same origin from where you execute the script. In the snippet below it will never work because these snippets run in a sandbox that prevents the use of this kind of external resources.

I'll leave this answer as an experiment:

jQuery(document).ready(function() {

    jQuery('#descargar').on('click', function() {
     
     jQuery('#loading').addClass('visible');
     
     var a = document.createElement('a');
     a.innerText='descargando';
		 a.target = '_blank';
		 a.download = 'mipdf.pdf';
     a.href="https://www.antennahouse.com/XSLsample/pdf/sample-link_1.pdf";
      
     document.getElementById('caja').appendChild(a);
          
     
      window.setTimeout(function() {
       a.click();
       jQuery('#loading').removeClass('visible');
     },1500);
   });

});
#caja {
height: 150px;
width:150px;
}
#descargar {
 padding:3px;
 border: 1px solid;
 width: 120px;
 cursor: pointer;
}

#milink {
  display:block;
  
}

#loading {
  opacity:0;
  height:100px;
  width:130px;
  transition: opacity: 1s;

}

#loading.visible {
  opacity: 1;
  transition: opacity 1s;
}
<script
  src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
  integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E="
  crossorigin="anonymous"></script>
  
  <div id="caja">
  <button id="descargar">Descarga el PDF</button>
  <img src="https://okcinjurylaw.com/assets/themes/okcinjurylaw/images/loading.gif" id="loading" />
  </div>

Most likely, firefox will actually take you to the PDF viewer of the document you wanted to download.

But since the document is served from the backend, in the same backend you could put a header that forces you to treat it as an attachment for download.

    
answered by 03.07.2018 в 14:58