Foros del Web » Programando para Internet » ASP Clásico »

subir fotos a BD

Estas en el tema de subir fotos a BD en el foro de ASP Clásico en Foros del Web. Hola a todos. Tengo en una pagina la opcion de subir una foto a la BD mediante un campo de archivo. En la BD viene ...
  #1 (permalink)  
Antiguo 10/01/2008, 08:35
 
Fecha de Ingreso: enero-2007
Mensajes: 284
Antigüedad: 17 años, 5 meses
Puntos: 1
subir fotos a BD

Hola a todos.
Tengo en una pagina la opcion de subir una foto a la BD mediante un campo de archivo. En la BD viene la foto como un MEDIUMBLOB, o sea q no subo el enlace sino la foto en sí. Todo esto me funciona genial.

El problema me surge cuando quiero que haya en la misma pagina la opcion de subir 2 fotos cada una con su correspondiente campo de archivo.
Ahi es cuando me estoy volviendo majareta.
Como lo puedo hacer?

Os dejo el codigo que tengo para subir 1 foto.

INSERT.ASP

<!--#include file="Uploader.asp"-->

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%

Response.Buffer = True

' load object
Dim load
Set load = new Uploader

' inicializando el objeto
load.initialize

' Datos binarios del fichero
Dim fileData
fileData = load.getFileData("file")
' Nombre del fichero
Dim fileName
fileName = LCase(load.getFileName("file"))
' Path del fichero
Dim filePath
filePath = load.getFilePath("file")
' Path completo del fichero
Dim filePathComplete
filePathComplete = load.getFilePathComplete("file")
' Tamano del fichero
Dim fileSize
fileSize = load.getFileSize("file")
' Tamano traducido del fichero
Dim fileSizeTranslated
fileSizeTranslated = load.getFileSizeTranslated("file")
' Tipo de fichero
Dim contentType
contentType = load.getContentType("file")
' No. de elementos del Form
Dim countElements
countElements = load.Count

' destruimos el objeto
Set load = Nothing
%>

<html>
<style type="text/css">
<!--
body {
background-color: #EAECEB;
}
-->
</style><head>
<title>Insertar imagen en base de datos</title>
</head>
<body>
<%
texto="foto1"
extension=right(filename,3)
if extension="jpg" or extension="gif" then
If fileSize > 1200000 Then%>
<script language="VBScript">
resultado = MSGBOX ("¡¡ERROR!!El tamaño de la foto es demasiado grande", VBCRITICAL, "SUBIR IMAGEN")
document.location.href="prueba.asp"
</script>
<%else
' Comprobamos que realmente se ha insertado el fichero en la base de datos
If fileSize > 0 Then

Dim connStr
Set connStr = Server.CreateObject("ADODB.Connection")
connStr.Open "Driver={MySQL ODBC 3.51 Driver};SERVER=localhost;Port=3306;Database=web;Ui d=root;Pwd=123123;Option=3;"


' Recordset
Dim rs
Set rs = Server.CreateObject("ADODB.Recordset")
rs.open "datos", connStr, 2, 2


' Insertando datos
rs.AddNew
rs("texto1")=texto
rs("foto1").AppendChunk fileData
rs("nombre1")=fileName
rs.Update


response.Redirect("prueba.asp")
%>

<%Else%>
<script language="VBScript">
resultado = MSGBOX ("¡¡ERROR!!No has seleccionado ninguna foto", VBCRITICAL, "SUBIR IMAGEN")
document.location.href="prueba.asp"
</script>
<%End If


End If

else%>
<script language="VBScript">
resultado = MSGBOX ("¡¡ERROR!!El archivo seleccionado no es una imagen", VBCRITICAL, "SUBIR IMAGEN")
document.location.href="prueba.asp"
</script>
<%end if%>
</body>
</html>

MOSTRAR.ASP
<%
Response.AddHeader "Pragma", "no-cache"
Response.AddHeader "cache-control","private"
Response.CacheControl = "no-cache"

Response.Buffer = True


' Cadena de conexion
Dim connStr
Set connStr = Server.CreateObject("ADODB.Connection")
connStr.Open "Driver={MySQL ODBC 3.51 Driver};SERVER=localhost;Port=3306;Database=web;Ui d=root;Pwd=123123;Option=3;"

' Recordset
Dim rs
Set rs = Server.CreateObject("ADODB.Recordset")

' abrimos la conexion
sql= "select foto1 from datos"
set rs=connStr.execute(sql)

Response.BinaryWrite rs("foto1")

rs.Close
Set rs = Nothing
%>

Y dentro de la pagina principal tengo(donde hago la llamada a mostrar la foto):

<form action="insert.asp" method="post" enctype="multipart/form-data" name="form1">
.....
<img src="mostrar.asp" alt="" name="foto1" width="100" height="135" border="1" id="foto1"></p>
<p>
<input type="file" name="file">
<input name="boton1" type="submit" id="boton1" value="aceptar">
....

Alguien me puede decir que opciones tengo?

GRACIAS.
  #2 (permalink)  
Antiguo 14/01/2008, 02:35
 
Fecha de Ingreso: enero-2007
Mensajes: 284
Antigüedad: 17 años, 5 meses
Puntos: 1
Re: subir fotos a BD

alguna idea please...
  #3 (permalink)  
Antiguo 16/01/2008, 06:32
 
Fecha de Ingreso: enero-2007
Mensajes: 284
Antigüedad: 17 años, 5 meses
Puntos: 1
Re: subir fotos a BD

De momento lo he solucionado insertando dos form en la pagina principal y que cada uno de ellos llame a un insertar y a un modificar diferente.

Es practicamente duplicar el codigo pero de momento es la unica solucion que encuentro.

Si alguien tiene alguna otra mas eficaz, aqui estoy para probarla.

Gracias.
  #4 (permalink)  
Antiguo 17/01/2008, 09:58
 
Fecha de Ingreso: enero-2007
Mensajes: 284
Antigüedad: 17 años, 5 meses
Puntos: 1
Re: subir fotos a BD

El problema que he encontrado a esto de los dos form es que uno de ellos me lo hace bien, y el otro me da un error.

Llamo a diferentes paginas y cuando lo ejecuto me da el error:

Error de Microsoft VBScript en tiempo de ejecución (0x800A0005)
Argumento o llamada a procedimiento no válidos: 'MidB'
/prueba/web/web_2008/Uploader.asp, line 136

el codigo de uploader es (en rojo la linea del error):

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%
Class Uploader
Private diccionario

Private Sub Class_Initialize
Set diccionario = Server.CreateObject("Scripting.Dictionary")
End Sub

Private Sub Class_Terminate
If IsObject(intDict) Then
intDict.RemoveAll
Set intDict = Nothing
End If
If IsObject(diccionario) Then
diccionario.RemoveAll
Set diccionario = Nothing
End If
End Sub

Public Property Get Count
Count = diccionario.Count
End Property

Public Sub Initialize
If Request.TotalBytes > 0 Then
Dim binData
binData = Request.BinaryRead(Request.TotalBytes)
getData binData
End If
End Sub

Public Function getFileData(name)
If diccionario.Exists(name) Then
getFileData = diccionario(name).Item("Value")
Else
getFileData = ""
End If
End Function

Public Function getValue(name)
Dim gv
If diccionario.Exists(name) Then
gv = CStr(diccionario(name).Item("Value"))

gv = Left(gv,Len(gv)-2)
getValue = gv
Else
getValue = ""
End If
End Function

Public Function saveToFile(name, path)
If diccionario.Exists(name) Then
Dim temp
temp = diccionario(name).Item("Value")
Dim fso
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Dim file
Set file = fso.CreateTextFile(path)
For tPoint = 1 to LenB(temp)
file.Write Chr(AscB(MidB(temp,tPoint,1)))
Next
file.Close
saveToFile = True
Else
saveToFile = False
End If
End Function

Public Function getFileName(name)
If diccionario.Exists(name) Then
Dim temp, tempPos
temp = diccionario(name).Item("FileName")
tempPos = 1 + InStrRev(temp, "\")
getFileName = Mid(temp, tempPos)
Else
getFileName = ""
End If
End Function

Public Function getFilePath(name)
If diccionario.Exists(name) Then
Dim temp, tempPos
temp = diccionario(name).Item("FileName")
tempPos = InStrRev(temp, "\")
getFilePath = Mid(temp, 1, tempPos)
Else
getFilePath = ""
End If
End Function

Public Function getFilePathComplete(name)
If diccionario.Exists(name) Then
getFilePathComplete = diccionario(name).Item("FileName")
Else
getFilePathComplete = ""
End If
End Function

Public Function getFileSize(name)
If diccionario.Exists(name) Then
getFileSize = LenB(diccionario(name).Item("Value"))
Else
getFileSize = 0
End If
End Function

Public Function getFileSizeTranslated(name)
If diccionario.Exists(name) Then
temp = 1 + LenB(diccionario(name).Item("Value"))
If Len(temp) <= 3 Then
getFileSizeTranslated = temp & " bytes"
ElseIf Len(temp) > 6 Then
temp = FormatNumber(((temp / 1024) / 1024), 2)
getFileSizeTranslated = temp & " megabytes"
Else
temp = FormatNumber((temp / 1024), 2)
getFileSizeTranslated = temp & " kilobytes"
End If
Else
getFileSizeTranslated = ""
End If
End Function

Public Function getContentType(name)
If diccionario.Exists(name) Then
getContentType = diccionario(name).Item("ContentType")
Else
getContentType = ""
End If
End Function

Private Sub getData(rawData)
Dim separator
separator = MidB(rawData, 1, InstrB(1, rawData, ChrB(13)) - 1)
Dim lenSeparator
lenSeparator = LenB(separator)

Dim currentPos
currentPos = 1
Dim inStrByte
inStrByte = 1
Dim value, mValue
Dim tempValue
tempValue = ""

While inStrByte > 0
inStrByte = InStrB(currentPos, rawData, separator)
mValue = inStrByte - currentPos

If mValue > 1 Then
value = MidB(rawData, currentPos, mValue)

Dim begPos, endPos, midValue, nValue
Dim intDict
Set intDict = Server.CreateObject("Scripting.Dictionary")

begPos = 1 + InStrB(1, value, ChrB(34))
endPos = InStrB(begPos + 1, value, ChrB(34))
nValue = endPos

Dim nameN
nameN = MidB(value, begPos, endPos - begPos)

Dim nameValue, isValid
isValid = True

If InStrB(1, value, stringToByte("Content-Type")) > 1 Then

begPos = 1 + InStrB(endPos + 1, value, ChrB(34))
endPos = InStrB(begPos + 1, value, ChrB(34))

If endPos = 0 Then
endPos = begPos + 1
isValid = False
End If

midValue = MidB(value, begPos, endPos - begPos)
intDict.Add "FileName", trim(byteToString(midValue))

begPos = 14 + InStrB(endPos + 1, value, stringToByte("Content-Type:"))
endPos = InStrB(begPos, value, ChrB(13))

midValue = MidB(value, begPos, endPos - begPos)
intDict.Add "ContentType", trim(byteToString(midValue))

begPos = endPos + 4
endPos = LenB(value)

nameValue = MidB(value, begPos, endPos - begPos)
Else
nameValue = trim(byteToString(MidB(value, nValue + 5)))
End If

If isValid = true Then
intDict.Add "Value", nameValue
intDict.Add "Name", nameN

diccionario.Add byteToString(nameN), intDict
End If
End If

currentPos = lenSeparator + inStrByte
Wend
End Sub

End Class

Private Function stringToByte(toConv)
Dim tempChar
For i = 1 to Len(toConv)
tempChar = Mid(toConv, i, 1)
stringToByte = stringToByte & chrB(AscB(tempChar))
Next
End Function

Private Function byteToString(toConv)
For i = 1 to LenB(toConv)
byteToString = byteToString & chr(AscB(MidB(toConv,i,1)))
Next
End Function
%>

alguna idea xq me da el error ese???????????

gracias.
  #5 (permalink)  
Antiguo 17/01/2008, 15:30
Avatar de Shiryu_Libra
Colaborador
 
Fecha de Ingreso: febrero-2007
Ubicación: Cantando "Screenager" en "Kirafa Kaput"
Mensajes: 3.614
Antigüedad: 17 años, 3 meses
Puntos: 88
Re: subir fotos a BD

no has mirado el codigo que usan en ESTA PAGINA, a lo mejor te evita todo el problema
__________________
"Eres parte del problema, parte de la solucion o parte del paisaje"
Un Saludo desde Desierto de Altar, Sonora, MX.
Shiryu_libra
  #6 (permalink)  
Antiguo 18/01/2008, 05:31
 
Fecha de Ingreso: enero-2007
Mensajes: 284
Antigüedad: 17 años, 5 meses
Puntos: 1
Re: subir fotos a BD

Ese codigo es elq uso yo tb.
El loader.asp es igual al uploader.asp q uso yo y q me da error.
Lo unico q cambia son los parametros q uso yo para mi web, en paginas como insert, show y demas... xq todo lo demas es lo mismo q utilizo yo.
  #7 (permalink)  
Antiguo 23/01/2008, 04:31
 
Fecha de Ingreso: enero-2007
Mensajes: 284
Antigüedad: 17 años, 5 meses
Puntos: 1
Re: subir fotos a BD

nadie sabe aq es debido el error???

una ayudita please!!!!!
  #8 (permalink)  
Antiguo 23/01/2008, 20:22
Avatar de virla  
Fecha de Ingreso: julio-2002
Ubicación: Rio Gallegos - Santa Cruz
Mensajes: 893
Antigüedad: 21 años, 11 meses
Puntos: 1
Re: subir fotos a BD

la mejor forma es guardar el path donde esta la foto, porque guardando la foto en la db se te pondra muy pesado y tarde o temprano te traera problemas
__________________
---->Sin ayuda no se llega a ningun lado<----
Virla
  #9 (permalink)  
Antiguo 24/01/2008, 10:34
 
Fecha de Ingreso: marzo-2005
Mensajes: 1
Antigüedad: 19 años, 2 meses
Puntos: 0
Re: subir fotos a BD

Cita:
Iniciado por baditxuk Ver Mensaje
nadie sabe aq es debido el error???

una ayudita please!!!!!
Baditux yo también tengo ese problema. El problema esta en el buffer de la base de datos que se queda corta. Yo tampoco he encontrado la solución de momente creer un objeto para cada pero no me acuerdo si lo pude solucionar . Si la encuentro te lo digo... Aunque a dia de hoy ya hay cosas mejores ado.net y ajax para hacer y por supuesto que si que se pueden guardar las imagenes en binario en un db. Saludos ;)
  #10 (permalink)  
Antiguo 24/01/2008, 11:29
Avatar de Shiryu_Libra
Colaborador
 
Fecha de Ingreso: febrero-2007
Ubicación: Cantando "Screenager" en "Kirafa Kaput"
Mensajes: 3.614
Antigüedad: 17 años, 3 meses
Puntos: 88
Re: subir fotos a BD

aqui estan los atributos de conexion a una base de datos utilizando el metodo ADO

Objeto de Conexion ADO

del cual podemos rescatar lo siguiente

Ejemplo:
Cita:
set objConnection=Server.CreateObject("ADODB.connectio n")
objConnection.CommandTimeout=10 Segundos para realizar la transaccion
objConnection.ConnectionString="Provider..... etc etc" la cadena de conexion
objConnection.ConnectionTimeout=10 establece el tiempo de espera para conexion
__________________
"Eres parte del problema, parte de la solucion o parte del paisaje"
Un Saludo desde Desierto de Altar, Sonora, MX.
Shiryu_libra
  #11 (permalink)  
Antiguo 25/01/2008, 03:14
 
Fecha de Ingreso: enero-2007
Mensajes: 284
Antigüedad: 17 años, 5 meses
Puntos: 1
Re: subir fotos a BD

Gracias.

Hasta que no encuentre la solución, creo que me declinaré por subir a la BD el path de la foto o el nombre solo de la foto.
1er paso -->En principio quiero copiar la foto seleccionada en una carpeta (lugar donde almacenare todas las fotos en el disco duro) y que me la visualize desde ahi (ejecutar el codigo en local).
2do paso -->Mas adelante cuando tenga todo creado, subiré la foto al servidor y la cargare desde ahi.

Alguien sabe donde encontrar el codigo de ambas cosas o que me eche una manita...

Gracias a tod@s.
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 23:10.