martes, febrero 20, 2007

¿Como almacenar una imagen JPG dentro de una Base de Datos con ASPX y C#?

Hace algunos meses escribí un pequeño artículo sobre como leer una imagen que se encuentra guardada en una base de datos, para desplegarla en una página web ASPX. Ahora, si nos hacemos la pregunta ¿como fue grabada esa imagen? Bueno, despues de un buen tiempo, aqui subo la respuesta:


¿como guardar una imagen en una base de datos?







public void btnSave_Click(object sender, System.EventArgs e)
{
Int32 iFileLength = System.Convert.ToInt32(fileUpload.PostedFile.InputStream.Length);
string sContentType = fileUpload.PostedFile.ContentType;
string sFileName = fileUpload.PostedFile.FileName.Substring(fileUpload.PostedFile.FileName.LastIndexOf("\\") + 1);
byte[] bFileDataBuffer = new byte[iFileLength + 1];
fileUpload.PostedFile.InputStream.Read(bFileDataBuffer, 0, iFileLength);

SqlTransaction trans=null;

con.Open();

try
{
trans = con.BeginTransaction();

spUploadInsertNew.Transaction = trans;
spUploadInsertNew.Parameters["@DocumentID"].Value = iDocumentID;
spUploadInsertNew.Parameters["@UserID"].Value = txtAuthor.Text;
spUploadInsertNew.Parameters["@Title"].Value = txtTitle.Text;
spUploadInsertNew.Parameters["@FileName"].Value = sFileName;
spUploadInsertNew.Parameters["@FileData"].Value = bFileDataBuffer;
spUploadInsertNew.Parameters["@ContentType"].Value = sContentType;
spUploadInsertNew.Parameters["@DatePosted"].Value = txtDatePosted.SelectedDate;
spUploadInsertNew.Parameters["@FileLength"].Value = iFileLength;

spUploadInsertNew.ExecuteNonQuery();

trans.Commit();

}
catch (Exception ex)
{
System.Console.WriteLine(ex.ToString());
trans.Rollback();
}
finally
{
con.Close();
}
}

Necesitamos un Stored Procedure como el siguiente:




/****** Object: Stored Procedure dbo.Uploads_I Script Date: 14/11/2006 03:49:32 p.m. ******/
CREATE PROCEDURE dbo.Uploads_I(
@DocumentID Integer,
@UserID CHAR(15),
@Title VARCHAR(45),
@FileName VARCHAR(85),
@FileData Image,
@ContentType VARCHAR(50),
@DatePosted DateTime,
@FileLength Integer)
AS
BEGIN
DECLARE @UploadID Integer

SELECT @UploadID = ISNULL(MAX(UploadID),0) + 1 FROM Uploads

INSERT INTO Uploads
([UploadID] ,[DocumentID] ,[UserID] ,[Title] ,[FileName] ,[FileData] ,[ContentType] ,[DatePosted] ,[FileLength] )
VALUES (@UploadID,@DocumentID,@UserID,@Title,@FileName,@FileData,@ContentType,@DatePosted,@FileLength)
END




No hay comentarios.:

Publicar un comentario