Visual Basic - GUARDAR Y ABRIR DOCUMENTOS PDF EN ASP .NET

Life is soft - evento anual de software empresarial
 
Vista:

GUARDAR Y ABRIR DOCUMENTOS PDF EN ASP .NET

Publicado por Manuel Lambis Ortiz (1 intervención) el 12/01/2009 23:08:03
Hola publico, les envio saludos a quien le interese mi nota, estuve realizando una practica donde mi proposito guardar archivos pdf en sql server y posteriormente descargarlo en una pagina .aspx, lo logre implementandolo en el lenguaje visual basic, no es complicado solo hay que tener tadas las herramientas del lenguaje clara, aqui les dejo el codigo para quien le interese y lo utilize en sus trabajos...

CLASE EN VISUAL BASIC PARA CARGAR EL ARCHIVO AL SERVIDOR Y GUARDARLO EN LA BASE DA DATOS

Imports System.Data.Sql
Imports System.IO
Imports System.Data.SqlClient

Partial Public Class IngresaPDF
Inherits System.Web.UI.Page
Dim tam As Integer
Dim nom As String
Dim sql As String
Dim ruta As String
Dim arreglo() As Char
'lectura de archivo
Dim archivo As FileStream

'conexion a BD
Dim conexion As SqlConnection
Dim sentencia As SqlCommand
Dim cadena As String = "Data Source = SERVIDOR BASE DE DATOS;
Initial Catalog =BASE DE DATOS; Integrated Security = True"
'parametros para procedimiento almacenado
Dim autor As SqlParameter
Dim apell As SqlParameter
Dim nombre As SqlParameter
Dim tama As SqlParameter
Dim arch As SqlParameter
Dim sw As Integer

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
If (FileUpload1.HasFile) Then
Try
'Obtener parametros a utilizar
nom = FileUpload1.FileName
tam = FileUpload1.FileBytes.Length
'NOTA: EL ARCHIVO PDF PRIMERO LO GUARDO EN UNA CARPETA EN EL
'SERVIDOR Y LUEGO LO LEO LOCALMENTE PARA GUARDARLO EN LA BD (FOLDER)
ruta = "C:folder" & nom
'Guardar Archivo en Carpeta Servidor
FileUpload1.SaveAs(ruta)
'leer archivo
archivo = New FileStream(ruta, FileMode.Open, FileAccess.Read)
Dim imagen(tam) As Byte
archivo.Read(imagen, 0, tam)
archivo.Close()
'Conexion a Base de Datos
conexion = New SqlConnection()
conexion.ConnectionString = cadena
'procedimiento almacenado
sql = "doc"
sentencia = New SqlCommand(sql, conexion)
sentencia.CommandType = CommandType.StoredProcedure
conexion.Open()
'parametros procedimiento almacenado
autor = New SqlParameter("@autor", SqlDbType.VarChar)
apell = New SqlParameter("@apell", SqlDbType.VarChar)
nombre = New SqlParameter("@pdf", SqlDbType.VarChar)
tama = New SqlParameter("@tam", SqlDbType.VarChar)
arch = New SqlParameter("@archivo", SqlDbType.Image)
'Establecer valores direccion del parametro
autor.Value = TextBox1.Text
autor.Direction = ParameterDirection.Input
apell.Value = TextBox2.Text
autor.Direction = ParameterDirection.Input
nombre.Value = nom
nombre.Direction = ParameterDirection.Input
tama.Value = tam
tama.Direction = ParameterDirection.Input
arch.Value = imagen
arch.Direction = ParameterDirection.Input
'agregar parametros al procedimiento
sentencia.Parameters.Add(autor)
sentencia.Parameters.Add(apell)
sentencia.Parameters.Add(nombre)
sentencia.Parameters.Add(tama)
sentencia.Parameters.Add(arch)
sw = sentencia.ExecuteNonQuery()
If (sw <> 0) Then
Label1.Text = "Archivo Guardado Satisfactoriamente"
End If
Catch ex As Exception
Label1.Text = "Problemas al Guardar Archivo: " & ex.Message
End Try
End If
End Sub
End Class

CREAR EL SIGUIENTE PROCEDIMIENTO ALMACENADO EN SQL SERVER PARA GUARDAR EL ARCHIVO PDF YA QUE NO ES POSIBLE CON LA SENTENCIA INSERT DIRECTAMENTE (HAY QUE CREAR LA TABLA DOCUMENTOS)

create procedure doc
@autor varchar(50)=null,
@apell varchar(50)=null,
@pdf varchar(50)=null,
@tam varchar(50)=null,
@archivo image=null
as
insert into documentos values(@autor,@apell,@pdf,@tam,@archivo)

POR ULTIMO LA CLASE PARA VISUALIZAR EL PDF EN EL NAVEGADOR WEB
LA DESCARLA DEL DOCUMENTO LA REALIZO POR LA INSERCION DEL NOMBRE Y APELLIDO DE QUIEN SUBIO EL PDF A LA BD, EN ESTE CASO PUEDES HACERLO CON UN SELECT O CON UN PROCEDIMIENTO ALMACENADO

CLASE DE DESCARGA DEL DOCUMENTO PDF

Imports System.Data.SqlClient
Imports System.IO
Partial Public Class DescargarPDF
Inherits System.Web.UI.Page
'conexion a BD
Dim conexion As SqlConnection
Dim sentencia As SqlCommand
Dim imagen As SqlDataReader
Dim cadena As String = "Data Source = SERVIDOR DB; Initial Catalog =BD;
Integrated Security = True"
Dim sql As String
'parametros entrada procedimiento almacenada
Dim aut As SqlParameter
Dim ape As SqlParameter
Dim documento As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
'conectara base de datos
conexion = New SqlConnection()
conexion.ConnectionString = cadena
sql = "select img from documentos where aut='" & TextBox1.Text & "'and apel='" & TextBox2.Text & "'"
sentencia = New SqlCommand(sql, conexion)
conexion.Open()
aut = New SqlParameter("@nombre", SqlDbType.VarChar)
ape = New SqlParameter("@apellido", SqlDbType.VarChar)
'parametros procedimiento almacenado
aut.Value = TextBox1.Text
aut.Direction = ParameterDirection.Input
ape.Value = TextBox2.Text
ape.Direction = ParameterDirection.Input
'agregar parametros
sentencia.Parameters.Add(aut)
sentencia.Parameters.Add(ape)
'ejecutar comando sql
imagen = sentencia.ExecuteReader()
Dim conv As New System.Text.ASCIIEncoding
'mostrar documentos pdf
If (imagen.Read) Then
Response.Buffer = True
Response.ContentType = "application/pdf"
Response.BinaryWrite(imagen(0))
End If
End Sub
End Class

AUTOR: MANUEL LAMBIS ORTIZ
SALUDOS
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

RE:GUARDAR Y ABRIR DOCUMENTOS PDF EN ASP .NET

Publicado por P3L30N2009 (699 intervenciones) el 13/01/2009 10:42:07
Se agradece la aportación, pero creo que te lo agradecerán mas si lo colocas en el foro de Visual Basic.Net (este es de VB6)

Saludos
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:GUARDAR Y ABRIR DOCUMENTOS PDF EN ASP .NET

Publicado por mireya (1 intervención) el 15/05/2009 01:00:01
Hola oye probe tu codigo pero me manda muchos errores donde te puedo contactar estoy tratando de hacer eso pero no me sale y ya estoy desesperada :S

Saludines
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:GUARDAR Y ABRIR DOCUMENTOS PDF EN ASP .NET

Publicado por Carlos Vives (1 intervención) el 15/09/2009 21:07:00
Lo probe tu ejemplo y corre solo cuando guarda el pdf, pero no lo despliega.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:GUARDAR Y ABRIR DOCUMENTOS PDF EN ASP .NET

Publicado por Jesus Ocampo (2 intervenciones) el 28/10/2010 16:35:05
Genial tu codigo funciona perfectamente lo unico que es necesario hacer algunas correcciones (no muy grandes) al codigo. Aqui pongo todo el codigo corregido.

PRIMERO EN LA PAGINA DE INGRESO DEL PDF.
Codigo HTML:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br /><br />

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" />

<br /><br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

Codigo VB:
'PRIMERO DEBEN IMPORTAR LAS CLASES
Imports System.IO
Imports System.Data.Sql
Imports System.Data.SqlClient

Partial Class IngresaPDF
Inherits System.Web.UI.Page

'Declaración de variables
Dim tam As Integer
Dim nom As String
Dim sql As String
Dim ruta As String
Dim arreglo() As Char
'lectura de archivo
Dim archivo As FileStream

'conexion a BD
Dim conexion As SqlConnection
Dim sentencia As SqlCommand
Dim cadena As String = "Data Source = SERVIDOR;Initial Catalog =BASE DE DATOS; Integrated Security = false; UID=USUARIO; PWD=CONTRASEÑA"
'parametros para procedimiento almacenado
Dim autor As SqlParameter
Dim apell As SqlParameter
Dim nombre As SqlParameter
Dim tama As SqlParameter
Dim arch As SqlParameter
Dim sw As Integer

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If (FileUpload1.HasFile) Then
Try
'Obtener parametros a utilizar
nom = FileUpload1.FileName
tam = FileUpload1.FileBytes.Length
'NOTA: EL ARCHIVO PDF PRIMERO LO GUARDO EN UNA CARPETA EN EL
'SERVIDOR Y LUEGO LO LEO LOCALMENTE PARA GUARDARLO EN LA BD (FOLDER)
ruta = "C:\" & nom 'DIRECCION EN EL SERVIDOR DONDE SE GUARDAR EL ARCHIVO FISICO
'Guardar Archivo en Carpeta Servidor
FileUpload1.SaveAs(ruta)
'leer archivo
archivo = New FileStream(ruta, FileMode.Open, FileAccess.Read)
Dim imagen(tam) As Byte
archivo.Read(imagen, 0, tam)
archivo.Close()
'Conexion a Base de Datos
conexion = New SqlConnection()
conexion.ConnectionString = cadena
'procedimiento almacenado
sql = "doc"
sentencia = New SqlCommand(sql, conexion)
sentencia.CommandType = Data.CommandType.StoredProcedure
conexion.Open()
'parametros procedimiento almacenado
autor = New SqlParameter("@autor", Data.SqlDbType.VarChar) 'Al SqlDbType.VarChar agregar el DATA.
apell = New SqlParameter("@apell", Data.SqlDbType.VarChar)
nombre = New SqlParameter("@pdf", Data.SqlDbType.VarChar)
tama = New SqlParameter("@tam", Data.SqlDbType.VarChar)
arch = New SqlParameter("@archivo", Data.SqlDbType.Image)
'Establecer valores direccion del parametro
autor.Value = TextBox1.Text
autor.Direction = Data.ParameterDirection.Input
apell.Value = TextBox2.Text
autor.Direction = Data.ParameterDirection.Input
nombre.Value = nom
nombre.Direction = Data.ParameterDirection.Input
tama.Value = tam
tama.Direction = Data.ParameterDirection.Input
arch.Value = imagen
arch.Direction = Data.ParameterDirection.Input
'agregar parametros al procedimiento
sentencia.Parameters.Add(autor)
sentencia.Parameters.Add(apell)
sentencia.Parameters.Add(nombre)
sentencia.Parameters.Add(tama)
sentencia.Parameters.Add(arch)
sw = sentencia.ExecuteNonQuery()
If (sw <> 0) Then
Label1.Text = "Archivo Guardado Satisfactoriamente"
End If
Catch ex As Exception
Label1.Text = "Problemas al Guardar Archivo: " & ex.Message
End Try
End If
End Sub
End Class

SEGUNDO PAGINA DE MUESTRA
CODIGO HTML:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" /></div>
<br /><br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

CODIGO VB:
Imports System.Data.SqlClient
Imports System.IO

Partial Class DescargarPDF
Inherits System.Web.UI.Page

'conexion a BD
Dim conexion As SqlConnection
Dim sentencia As SqlCommand
Dim imagen As SqlDataReader
Dim cadena As String = "Data Source = SERVIDOR;Initial Catalog =BASE DE DATOS; Integrated Security = false; UID=USUARIO; PWD=CONTRASEÑA"
Dim sql As String
'parametros entrada procedimiento almacenada
Dim aut As SqlParameter
Dim ape As SqlParameter
Dim documento As String

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.TextBox1.Text = "PRIMER TEXTO"
Me.TextBox2.Text = "SEGUNDO TEXTO"
End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
'conectara base de datos
conexion = New SqlConnection()
conexion.ConnectionString = cadena
sql = "SELECT * FROM tblDoc WHERE autor = '" & Me.TextBox1.Text.Trim & "' AND apell = '" & Me.TextBox2.Text.Trim & "'"
sentencia = New SqlCommand(sql, conexion)
conexion.Open()
aut = New SqlParameter("@nombre", Data.SqlDbType.VarChar)
ape = New SqlParameter("@apellido", Data.SqlDbType.VarChar)
'parametros procedimiento almacenado
aut.Value = TextBox1.Text
aut.Direction = Data.ParameterDirection.Input
ape.Value = TextBox2.Text
ape.Direction = Data.ParameterDirection.Input
'agregar parametros
sentencia.Parameters.Add(aut)
sentencia.Parameters.Add(ape)
'ejecutar comando sql
imagen = sentencia.ExecuteReader()

Dim conv As New System.Text.ASCIIEncoding
'mostrar documentos pdf
If (imagen.Read) Then
Response.Buffer = True
Response.ContentType = "application/pdf"
Response.BinaryWrite(imagen("archivo"))'ESTA ES LA PARTE MAS IMPORTANTE, DEBEN TENER EL CUIDADO QUE EL "archivo" SEA REMPLAZADO POR EL NOMBRE DE LA COLUMNA DE LA BASE DE DATOS EN DONDE ESTA GUARDADO EL PDF O BIEN REMPLAZARLO POR EL INDEX DEL MISMO PERO SIN LAS COMILLAS.
End If

Catch ex As Exception
Me.Label1.Text = "Ha ocurrido un error: " & ex.Message
End Try
End Sub
End Class
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:GUARDAR Y ABRIR DOCUMENTOS PDF EN ASP .NET

Publicado por Jesus Ocampo (2 intervenciones) el 28/10/2010 18:12:42
OK, les traigo el codigo optimizado corriendo para OLDB. Lo tratare de explicar paso a paso para quienes quieran utilizarlo.

Tabla en sql:
create table tblDoc
(
autor NVARCHAR(50) NULL,
apell NVARCHAR(50) NULL,
pdf NVARCHAR(50) NULL,
tam NVARCHAR(50) NULL,
archivo IMAGE NULL
)

Procedimiento almacenado de sql:
CREATE procedure [dbo].[doc]
@autor varchar(50),
@apell varchar(50),
@pdf varchar(50),
@tam varchar(50),
@archivo image
AS
INSERT INTO tblDoc VALUES(@autor,@apell,@pdf,@tam,@archivo)

Pagina de Ingreso: Codigo HTML:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br /><br />

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" />

<br /><br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

Pagina de Ingreso: Codigo VB:
'Importamos las librerias a utilizar
Imports System.IO
Imports System.Data

Partial Class IngresaPDF
Inherits System.Web.UI.Page

'Declaración de variables
Dim tam As Integer
Dim nom As String
Dim sql As String
Dim ruta As String
Dim arreglo() As Char
Dim archivo As FileStream

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
sp_FormaModificada()
End Sub

Private Sub sp_FormaModificada()
If (FileUpload1.HasFile) Then
Dim dbcon As New System.Data.OleDb.OleDbConnection("Provider=SQLNCLI;Server=SERVIDOR;Database=BASE DE DATOS;UID=USUARIO;PWD=CONTRASEÑA")
Try
nom = FileUpload1.FileName 'NOMBRE DEL ARCHIV0
tam = FileUpload1.FileBytes.Length 'TAMAÑO DEL ARCHIVO
ruta = Server.MapPath("pdf\") & nom 'RUTA DONDE SE GUARDARA EL ARCHIVO
FileUpload1.SaveAs(ruta) 'GUARDANDO EL ARCHIVO

'EMPIEZA LECTURA DEL ARCHIVO
archivo = New FileStream(ruta, FileMode.Open, FileAccess.Read)
Dim imagen(tam) As Byte
archivo.Read(imagen, 0, tam)
archivo.Close()

'' '' '' ''
'' '' PROCEDIMIENTO DE GUARDADO EN LA BASE DE DATOS
'' '' '' ''
If dbcon.State = ConnectionState.Closed Then
dbcon.Open()
End If

sql = "doc ?,?,?,?,?"
Dim cmd As New OleDb.OleDbCommand(sql, dbcon)

'parametros procedimiento almacenado
cmd.Parameters.Add("@autor", OleDb.OleDbType.VarChar, 50).Value = Me.TextBox1.Text.Trim
cmd.Parameters.Add("@apell", OleDb.OleDbType.VarChar, 50).Value = Me.TextBox2.Text.Trim
cmd.Parameters.Add("@pdf", OleDb.OleDbType.VarChar, 50).Value = nom
cmd.Parameters.Add("@tam", OleDb.OleDbType.VarChar, 50).Value = tam
cmd.Parameters.Add("@archivo", OleDb.OleDbType.Binary, imagen.Length).Value = imagen
sw = cmd.ExecuteNonQuery

If (sw <> 0) Then
Label1.Text = "Archivo Guardado Satisfactoriamente"
End If

Catch ex As Exception
Label1.Text = "Problemas al Guardar Archivo: " & ex.Message

Finally
If dbcon.State = ConnectionState.Open Then
dbcon.Close()
End If
End Try
End If
End Sub
End Class

Pagina de Visualizacion: Codigo HTML:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" /></div>
<br /><br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

Pagina de Visualizacion: Codigo VB:
'Importamos las librerias a utilizar
Imports System.IO
Imports System.Data

Partial Class DescargarPDF
Inherits System.Web.UI.Page

Dim sql As String
Dim documento As String

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
sp_CargaPDF_Modificado()
End Sub

Private Sub sp_CargaPDF_Modificado()
Dim dbcon As New System.Data.OleDb.OleDbConnection("Provider=SQLNCLI;Server=SERVIDOR;Database=BASE DE DATOS;UID=USUARIO;PWD=CONTRASEÑA")
Try
'' '' '' ''
'' '' PROCEDIMIENTO DE GUARDADO EN LA BASE DE DATOS
'' '' '' ''
If dbcon.State = ConnectionState.Closed Then
dbcon.Open()
End If

sql = "SELECT * FROM tblDoc WHERE autor = '" & Me.TextBox1.Text.Trim & "' AND apell = '" & Me.TextBox2.Text.Trim & "'"
Dim cmd As New OleDb.OleDbCommand(sql, dbcon)

Dim imagen As OleDb.OleDbDataReader
imagen = cmd.ExecuteReader
Dim conv As New System.Text.ASCIIEncoding
If (imagen.Read) Then
Response.Buffer = True
Response.ContentType = "application/pdf"
Response.BinaryWrite(imagen("archivo"))
'Deben remplazar el nombre "archivo" por el nombre de la columna en donde
'se almacena el pdf

End If

Catch ex As Exception
Me.Label1.Text = "Ha ocurrido un error: " & ex.Message
End Try
End Sub
End Class
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:GUARDAR Y ABRIR DOCUMENTOS PDF EN ASP .NET

Publicado por victor (1 intervención) el 16/03/2012 23:35:03
el codigo esta super bueno pero tengo un problema cuando muesta el archivo lo miestar en codigos ni me muestra el alchivo como lo guarde que se ra mi erros si me pueden ayudar se los agradezco
yo tengo el codigo =
cuando guardo imagenes si mes las abre normal mente el problema es con los pdf o archivos de texto
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar