J'ai un site Web asp.net qui permet à l'utilisateur de télécharger des fichiers volumineux - de 30 Mo à environ 60 Mo. Parfois, le téléchargement fonctionne bien, mais il échoue souvent à un moment donné avant que le téléchargement ne se termine avec le message indiquant que la connexion avec le serveur a été réinitialisée. À l'origine, j'utilisais simplement Server.TransmitFile mais après avoir lu un peu, j'utilise maintenant le code affiché ci-dessous. Je définis également la valeur Server.ScriptTimeout à 3600 dans l'événement Page_Init.Téléchargement de fichiers volumineux - Connexion avec réinitialisation du serveur
private void DownloadFile(string fname, bool forceDownload)
{
string path = MapPath(fname);
string name = Path.GetFileName(path);
string ext = Path.GetExtension(path);
string type = "";
// set known types based on file extension
if (ext != null)
{
switch (ext.ToLower())
{
case ".mp3":
type = "audio/mpeg";
break;
case ".htm":
case ".html":
type = "text/HTML";
break;
case ".txt":
type = "text/plain";
break;
case ".doc":
case ".rtf":
type = "Application/msword";
break;
}
}
if (forceDownload)
{
Response.AppendHeader("content-disposition",
"attachment; filename=" + name.Replace(" ", "_"));
}
if (type != "")
{
Response.ContentType = type;
}
else
{
Response.ContentType = "application/x-msdownload";
}
System.IO.Stream iStream = null;
// Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[10000];
// Length of the file:
int length;
// Total bytes to read:
long dataToRead;
try
{
// Open the file.
iStream = new System.IO.FileStream(path, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;
//Response.ContentType = "application/octet-stream";
//Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
// Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);
// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);
// Flush the data to the HTML output.
Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch (Exception ex)
{
// Trap the error, if any.
Response.Write("Error : " + ex.Message);
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
Response.Close();
}
}
Pourquoi? Pourriez-vous s'il vous plaît expliquer la raison? –