PuntoBit

Noviembre 7, 2007

Transferir Archivos con ASP.Net

Archivado en: ASP.Net, Desarrollo — Etiquetas:, , , , , , , — A l e x a n d e r @ 11:50 pm

A continuación un ejemplo de cómo transferir un archivo al cliente en ASP.Net.
Una forma alternativa al método TransmitFile() de la clase HttpResponse.
Dicho método (disponible a partir del Framework 2.0), si bien resulta práctico, puede ser poco útil en ciertas circunstancias.
Según la MSDN 2005

Writes the specified file directly to an HTTP response output stream without buffering it in memory.

Lo cual nos deja bastante en claro que servirá casi exclusivamente para archivos de tamaño menor ya que no hace ningún buffering de los datos en memoria.

Otra limitación es que no se nos permite definir el nombre de archivo que verá el cliente a la hora de iniciar la descarga. Muchas veces deseamos modificarlo para presentarle al cliente un nombre mas amigable y/o por cuestiones de seguridad.

Buscar una opción a TransmitFile() puede también ser necesario cuando se trabaja bajo ciertos escenarios (mi caso, la utilización de un framework de desarrollo) en los cuales el método provisto por Microsoft no logra el resultado esperado.

Sin más, el código …

Protected Sub Transferir_Archivo(ByVal sArchivo As String)
  ‘Si el archivo existe en disco …
  If IO.File.Exists(sArchivo) Then
    ‘Tamanio del buffer en bytes
    Const LONGITUD_BUFFER As Integer = 1024
    Dim DownloadStream As FileStream
    Dim Leidos, FileSize As Long
    Dim Buffer() As Byte = New Byte(LONGITUD_BUFFER) {}
    DownloadStream = File.OpenRead(sArchivo)
    FileSize = DownloadStream.Length   
    Response.Buffer = False
    Response.ClearHeaders()
    Response.ClearContent()
    Response.ContentType = “application/octet-stream”
    Response.AddHeader(“Content-Length”, FileSize)
    Response.AddHeader(“Content-Disposition”, “attachment; filename=” + “nombre.ext”)
    Leidos = DownloadStream.Read(Buffer, 0, Buffer.Length)’
    Si lei bytes del archivo …
     While (Leidos > 0)
         ‘Y el cliente sigue conectado …
         If (Context.Response.IsClientConnected) Then
             ‘Se le envian bytes
             Context.Response.OutputStream.Write(Buffer, 0, Leidos)
         End If
    ‘Re-inicializo el buffer
    Array.Clear(Buffer, 0, Buffer.Length)
    Leidos = DownloadStream.Read(Buffer, 0, Buffer.Length)
  End While
  Context.Response.Flush()
  DownloadStream.Close()
  Response.End()
  Else
    Throw new Exception(“Error: No se encontró el archivo.”)
  End If
End Sub

Blog de WordPress.com.