Barra laterale

programmazione:jquery:download_di_file_con_ajax

Download di file con $.ajax() di jquery

Autore: Fabio Di Matteo
Ultima revisione: 25/06/2014 - 00:09

In questo articolo vedremo come scaricare un file html,testo,xml e visualizzarso in un div, mostrando anche la percentuale di download.

<html >
<head>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<title>Esperimento</title>
<script type="text/javascript">
 
         $(document).ready(function(){
            $("#mybutton").click(function(e){ //intercetto il submit del form
                 $('#progress').html('');
                 $.ajax({
				url: $('#myinput').val(),
				type: 'GET',
				timeout:30000,
				async: true,
				crossDomain: true,
				cache: false,
				dataType: "html",
				processData: false, //per i form "multipart/form-data"
				beforeSend: function () {
					  $('#outputServer').html('Download in corso...');
					  $('#mybutton').attr("disabled", "disabled");
				},
				success: function (data) {
					  $('#outputServer').html(data);//il file verra' mostrato in '#outputServer'
				},
				error: function(){
					$('#outputServer').html('Errore inatteso...');
				},
				complete: function(){
					$('#mybutton').removeAttr("disabled");
				},
				xhr: function(){
					// prende il riferimento all'oggetto nativo 'XmlHttpRequest' 
					var xhr = $.ajaxSettings.xhr() ;
					// callback per l'evento onprogress
					xhr.onprogress = function(evt){ $('#progress').html(Math.round(evt.loaded/evt.total*100)+'%') } ;
					// callback per l'evento 'onload' , ovvero caricamento finito
					xhr.onload = function(){ $('#progress').html('100% - caricamento completato.') };
					// ritorna l'oggetto xhr
					return xhr ;  
				}
 
			  });
 
 
		});
 
 
       });
 
 
</script>
 
</head>
<body>
 
<input type="text" id="myinput">
<button id="mybutton">Scarica </button>
<div id="progress">0%</div >
<pre id="outputServer" style="border: 1px Solid gray; width: 50%"></pre>
 
 
</body>
</html>

programmazione/jquery/download_di_file_con_ajax.txt · Ultima modifica: 18/04/2018 - 15:49 (modifica esterna)