2011-01-13 16 views
10

Ho una finestra popup che mostra "Attendere il download del file". Questo popup esegue anche il codice qui sotto per avviare il download del file. Come posso chiudere la finestra popup una volta completato il download del file? Ho bisogno di un modo per rilevare che il download del file è stato completato così posso chiamare self.close() per chiudere questo popup.Come posso rilevare quando il download di un file è stato completato in ASP.NET?

System.Web.HttpContext.Current.Response.ClearContent(); 
System.Web.HttpContext.Current.Response.Clear(); 
System.Web.HttpContext.Current.Response.ClearHeaders(); 
System.Web.HttpContext.Current.Response.ContentType = fileObject.ContentType; 
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", string.Concat("attachment; filename=", fileObject.FileName)); 
System.Web.HttpContext.Current.Response.WriteFile(fileObject.FilePath); 
Response.Flush(); 
Response.End(); 
+7

risposta breve ... non è possibile! –

+0

Il download è lato client, ASP.NET è lato server. –

+1

Non puoi. Perché bloccare l'interfaccia utente in attesa di un download. Sicuramente il corretto funzionamento della tua pagina può continuare senza una tale attesa in quanto non può esserci una dipendenza dal file scaricato. Il Web non funziona in questo modo, perché vuoi? – spender

risposta

0

Alcuni hack sono circa che coinvolge sapere quando l'ultimo pezzo del buffer è stato inviato o il controllo della proprietà HttpResponse.IsClientConnected.

0

Gestisco il problema in modo diverso in Javascript, che potrebbe o non potrebbe funzionare per voi.

  • Creare un elemento DIV nascosta, con il messaggio 'File sta scaricando ...' piuttosto che una finestra pop-up.
  • Mostra il div quando il download inizia
  • Una volta che qualsiasi altro elemento sulle forme viene cliccato, nascondere il div nuovo ..
  • È anche possibile impostare un timer per nascondere il download messaggio div dopo così quantità di tempo ...

ho dato una volta l'utente fa clic su un altro elemento, che sia già conosce il download è fatto, o lei è pronta a fare qualcosa di diverso, in modo che il messaggio diventa irrilevante e può andare via ....

2

Un'idea:

Se si gestisce il download di file da soli nel codice lato server scrivendo blocco per blocco al flusso di risposta, allora saprete quando il file ha avuto scaricamento finito. Dovresti semplicemente collegare FileStream al flusso di risposta, inviare blocchi di dati per blocco e reindirizzare dopo il completamento. Questo può essere all'interno della finestra popup.

Response.ContentType = "application/octet-stream"; 
Response.AppendHeader("content-disposition", "attachment; filename=bob.mp3"); 
Response.AppendHeader("content-length", "123456789"); 

Assicurarsi di selezionare Response.IsClientConnected quando si scrive sul flusso di risposta.

0

Il modo per farlo è nel pop-up per chiamare il server tramite il polling AJAX per una risposta che indicherebbe che il file è stato svuotato.

Es: subito prima di inviare il file, memorizzare sessionID + FileName in un DB o sessione o cosa avete.

Sul client, nel pop-up, il polling di un web-service tramite la tecnologia AJAX - questo potrebbe anche essere un WebMethod come Bool IsContentFlushed(string sessionID, string fileName);

Dopo non Response.Flush(); rimuovere questo sessionID + FileName dal vostro negozio.

Chiama Response.Close() anziché Response.End() - il più tardi è molto brutale e di solito è over-kill.

1

Esiste una soluzione in cui è possibile tenere traccia dello stato del download trasferendo il file come pacchetti più piccoli e verificare se tutti i pacchetti sono stati trasferiti. La soluzione non è mia, ma si può trovare qui: File Download in ASP.NET and Tracking the Status of Success/Failure of Download

//Function for File Download in ASP.Net in C# and 
//Tracking the status of success/failure of Download. 
private bool DownloadableProduct_Tracking() 
{ 
//File Path and File Name 
string filePath = Server.MapPath("~/ApplicationData/DownloadableProducts"); 
string _DownloadableProductFileName = "DownloadableProduct_FileName.pdf"; 

System.IO.FileInfo FileName = new System.IO.FileInfo(filePath + "\\" + _DownloadableProductFileName); 
FileStream myFile = new FileStream(filePath + "\\" + _DownloadableProductFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 

//Reads file as binary values 
BinaryReader _BinaryReader = new BinaryReader(myFile); 

//Ckeck whether user is eligible to download the file 
if (IsEligibleUser()) 
{ 
//Check whether file exists in specified location 
if (FileName.Exists) 
{ 
    try 
    { 
    long startBytes = 0; 
    string lastUpdateTiemStamp = File.GetLastWriteTimeUtc(filePath).ToString("r"); 
    string _EncodedData = HttpUtility.UrlEncode(_DownloadableProductFileName, Encoding.UTF8) + lastUpdateTiemStamp; 

    Response.Clear(); 
    Response.Buffer = false; 
    Response.AddHeader("Accept-Ranges", "bytes"); 
    Response.AppendHeader("ETag", "\"" + _EncodedData + "\""); 
    Response.AppendHeader("Last-Modified", lastUpdateTiemStamp); 
    Response.ContentType = "application/octet-stream"; 
    Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName.Name); 
    Response.AddHeader("Content-Length", (FileName.Length - startBytes).ToString()); 
    Response.AddHeader("Connection", "Keep-Alive"); 
    Response.ContentEncoding = Encoding.UTF8; 

    //Send data 
    _BinaryReader.BaseStream.Seek(startBytes, SeekOrigin.Begin); 

    //Dividing the data in 1024 bytes package 
    int maxCount = (int)Math.Ceiling((FileName.Length - startBytes + 0.0)/1024); 

    //Download in block of 1024 bytes 
    int i; 
    for (i = 0; i < maxCount && Response.IsClientConnected; i++) 
    { 
     Response.BinaryWrite(_BinaryReader.ReadBytes(1024)); 
     Response.Flush(); 
    } 
    //if blocks transfered not equals total number of blocks 
    if (i < maxCount) 
     return false; 
    return true; 
    } 
    catch 
    { 
    return false; 
    } 
    finally 
    { 
    Response.End(); 
    _BinaryReader.Close(); 
    myFile.Close(); 
    } 
} 
else System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), 
    "FileNotFoundWarning","alert('File is not available now!')", true); 
} 
else 
{ 
System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), 
    "NotEligibleWarning", "alert('Sorry! File is not available for you')", true); 
} 
return false; 
} 
Problemi correlati