2012-09-14 17 views
8

Me gustaría usar HttpResponse.OutputStream junto con ContentResult para que pueda Flush de vez en cuando para evitar el uso de demasiada memoria RAM por .Net.¿Cómo transmitir correctamente grandes datos desde MVC3 sin usar demasiada memoria RAM?

Pero todos los ejemplos con MVC FileStreamResult, EmptyResult, FileResult, ActionResult, ContentResult muestran el código que obtiene todos los datos en la memoria y los pasa a uno de esos. También una publicación sugiere que devolver EmptyResult junto con usar HttpResponse.OutputStream es una mala idea. ¿De qué otra manera puedo hacer eso en MVC?

¿Cuál es la forma correcta de organizar la salida de big data (html o binary) desde el servidor MVC?

¿Por qué devolver EmptyResult o ContentResult o FileStreamResult es una mala idea?

+0

¿Alguien tiene alguna información sobre el uso de las cañerías que se mencionan en http://stackoverflow.com/a/2189635/37055 –

Respuesta

5

Querrá utilizar FileStreamResult si ya tenía una secuencia para trabajar. Muchas veces, es posible que solo tengas acceso al archivo, necesites construir una secuencia y luego enviarla al cliente.

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; 

// Identify the file to download including its path. 
string filepath = "DownloadFileName"; 

// Identify the file name. 
string filename = System.IO.Path.GetFileName(filepath); 

try 
{ 
    // Open the file. 
    iStream = new System.IO.FileStream(filepath, 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(); 
} 

Here es el artículo de Microsoft que explica el código de seguridad.

Cuestiones relacionadas