6

Actualmente estoy usando una HttpResponse para descargar archivos de mi servidor. Ya tengo un par de funciones que se utilizan para descargar archivos de Excel/Word, pero tengo problemas para descargar mi archivo de texto simple (.txt).Response.TransmitFile No descargando y no lanzando errores

Con el archivo de texto básicamente estoy volcando contenido de un TextBox en un archivo, intentando descargar el archivo con HttpResponse y luego borrando el archivo de texto temporal.

Aquí es un ejemplo de mi código que funcione para los documentos de Excel/Word:

protected void linkInstructions_Click(object sender, EventArgs e) 
{ 
    String FileName = "BulkAdd_Instructions.doc"; 
    String FilePath = Server.MapPath("~/TempFiles/BulkAdd_Instructions.doc"); 
    System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; 
    response.ClearContent(); 
    response.Clear(); 
    response.ContentType = "application/x-unknown"; 
    response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";"); 
    response.TransmitFile(FilePath); 
    response.Flush(); 
    response.End(); 
} 

Y aquí es el trozo de código que no funciona.
Tomando en cuenta que el código se ejecuta sin lanzar ningún error. El archivo se crea y borra, pero nunca se descarga al usuario.

protected void saveLog(object sender, EventArgs e) 
{ 
    string date = DateTime.Now.ToString("MM_dd_yyyy_hhmm");  // Get Date/Time 
    string fileName = "BulkLog_"+ date + ".txt";    // Stitch File Name + Date/Time 
    string logText = errorLog.Text;        // Get Text from TextBox 
    string halfPath = "~/TempFiles/" + fileName;    // Add File Name to Path 
    string mappedPath = Server.MapPath(halfPath);    // Create Full Path 

    File.WriteAllText(mappedPath, logText);      // Write All Text to File 

    System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; 
    response.ClearContent(); 
    response.Clear(); 
    response.ContentType = "text/plain"; 
    response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); 
    response.TransmitFile(mappedPath);    // Transmit File 
    response.Flush(); 

    System.IO.File.Delete(mappedPath);    // Delete Temporary Log 
    response.End(); 
} 

Respuesta

-5

terminé fijación de la cuestión por mi cuenta. Resultó que era un problema de Ajax que no permitía que mi botón funcionara adecuadamente. Esto detuvo el TransmitFile de ser despedido.

¡Gracias por la ayuda!

+0

¿Cómo lo resolvió? Estoy teniendo exactamente el mismo problema. Mi ModalpopupExtender/UpdatePanel evita que mi botón que inicia mi descarga de archivos funcione. Cuando muevo ese botón fuera de mi modalpopupextender/updatepanel, funciona sin problemas. – JoeManiaci

+3

Gracias por informarnos que lo solucionó y no ayudó con cómo. – Danrex

+0

Decirnos CÓMO lo arreglaste habría sido agradable – Nevyn

10

Es porque está borrando el archivo antes de poder enviarlo.

De MSDN - HttpResponse.End Method

envía todos atenuado actualmente de salida a el cliente, se detiene la ejecución de la página , y genera el evento EndRequest.

Intente poner su System.IO.File.Delete (mappedPath); línea después de la respuesta. End(); en mi prueba en ese momento parecía estar funcionando.

Además, podría ser una buena idea comprobar si el archivo existe primero, no puede ver ningún archivo. Existir allí, no desea ninguna excepción de referencia nula, y establecer Content-Length.

EDITAR: aquí está el código que utilicé en un proyecto en el trabajo hace un tiempo, podría ayudarlo un poco.

// Get the physical Path of the file 
string filepath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + folder + filename; 

// Create New instance of FileInfo class to get the properties of the file being downloaded 
FileInfo file = new FileInfo(filepath); 

// Checking if file exists 
if (file.Exists) 
{        
    // Clear the content of the response 
    Response.ClearContent(); 

    // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header 
    Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", file.Name)); 

    // Add the file size into the response header 
    Response.AddHeader("Content-Length", file.Length.ToString()); 

    // Set the ContentType 
    Response.ContentType = ReturnFiletype(file.Extension.ToLower()); 

    // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead) 
    Response.TransmitFile(file.FullName); 

    // End the response 
    Response.End(); 

    //send statistics to the class 
} 

Y aquí es el método Filetype Solía ​​

//return the filetype to tell the browser. 
//defaults to "application/octet-stream" if it cant find a match, as this works for all file types. 
public static string ReturnFiletype(string fileExtension) 
{ 
    switch (fileExtension) 
    { 
     case ".htm": 
     case ".html": 
     case ".log": 
      return "text/HTML"; 
     case ".txt": 
      return "text/plain"; 
     case ".doc": 
      return "application/ms-word"; 
     case ".tiff": 
     case ".tif": 
      return "image/tiff"; 
     case ".asf": 
      return "video/x-ms-asf"; 
     case ".avi": 
      return "video/avi"; 
     case ".zip": 
      return "application/zip"; 
     case ".xls": 
     case ".csv": 
      return "application/vnd.ms-excel"; 
     case ".gif": 
      return "image/gif"; 
     case ".jpg": 
     case "jpeg": 
      return "image/jpeg"; 
     case ".bmp": 
      return "image/bmp"; 
     case ".wav": 
      return "audio/wav"; 
     case ".mp3": 
      return "audio/mpeg3"; 
     case ".mpg": 
     case "mpeg": 
      return "video/mpeg"; 
     case ".rtf": 
      return "application/rtf"; 
     case ".asp": 
      return "text/asp"; 
     case ".pdf": 
      return "application/pdf"; 
     case ".fdf": 
      return "application/vnd.fdf"; 
     case ".ppt": 
      return "application/mspowerpoint"; 
     case ".dwg": 
      return "image/vnd.dwg"; 
     case ".msg": 
      return "application/msoutlook"; 
     case ".xml": 
     case ".sdxl": 
      return "application/xml"; 
     case ".xdp": 
      return "application/vnd.adobe.xdp+xml"; 
     default: 
      return "application/octet-stream"; 
    } 
} 
+0

Por desgracia, también había tratado inicialmente esto. En mi caso, cuando muevo la línea Eliminar debajo de la respuesta. Fin() omite por completo la línea Eliminar, interrumpiendo la respuesta. Fin(). También intenté eliminar la línea Eliminar por completo, pero todavía no tuve suerte. – Lando

2

Gracias por el seguimiento de cuál fue su problema. He pasado horas tratando de descubrir por qué no se lanzó ningún código de error a pesar de que no pasó nada. Resulta que fue mi AJAX UpdatePanel misterioso y encubierto en el camino.

0

También intente this para guardar texto en el lado del cliente (Chrome solamente ahora) sin el viaje de ida y vuelta al servidor.

Here es otra base de flash de uno ...

1

me encontré con este post en mi búsqueda, y se dio cuenta de que no era útil en decirnos por qué el UpdatePanel causó el problema en primer lugar.

UpdatePanel es una devolución de datos asincrónica, y Response.TransmitFile necesita una devolución de datos completa para que funcione correctamente.

El control que activa la devolución de datos asincrónica es necesario hacer un disparador en el UpdatePanel:

<Triggers>   
<asp:PostBackTrigger ControlID="ID_of_your_control_that_causes_postback" /> 
</Triggers> 
Cuestiones relacionadas