by lukiller:
22. January 2010 03:12
En el artículo anterior mostramos como insertar imágenes en una base de datos, ahora vamos a ver como obtenerlas para mostrarlas en una página web. Lo vamos a hacer utilizando Generic Handlers. Creamos un archivo llamado "VerArchivo.ashx" y colocamos lo siguiente en el método ProcessRequest:
public void ProcessRequest(HttpContext context)
{
int id = 3; //Este valor puede venir de Querystring o de donde sea.
using (SqlConnection cn = new SqlConnection(_cadenaConexion))
{
SqlCommand cm = new SqlCommand("spArchivo", cn);
cm.CommandType = CommandType.StoredProcedure;
cm.Parameters.Add(new SqlParameter("@Id", id));
SqlDataAdapter da = new SqlDataAdapter(cm);
DataTable dt = new DataTable();
da.Fill(dt);
System.IO.MemoryStream mem = new System.IO.MemoryStream();
byte[] buffer = (byte[])(dt.Rows[0]["Archivo"]);
mem.Write(buffer, 0, buffer.Length);
context.Response.Expires = 0;
context.Response.Buffer = true;
context.Response.Clear();
context.Response.ContentType = "image/jpeg";
mem.WriteTo(context.Response.OutputStream);
context.Response.End();
}
}
El stored procedure mediante el cual vamos a obtener el contenido de la imagen es el siguiente:
CREATE PROCEDURE spArchivo
@Id AS INT
AS
SELECT Nombre, Archivo
FROM Archivos
WHERE Id = @Id
Para mostrar la imagen agregamos un tag "img" en cualquier archivo aspx, llamando al handler "VerArchivo.ashx":
<img src="VerArchivo.ashx" alt="Archivo de BD" />
fa8b1bfd-10a5-4ba3-8850-1a5ea618cfe9|1|5.0
Tags: