Saving and Reading Images in Oracle with classic asp - oracle

i am utilizing aspSmartUpload to upload an image into an Oracle BLOB field, see below:
Set mySmartUpload = Server.CreateObject("aspSmartUpload.SmartUpload")
'*** Upload Files ***'
mySmartUpload.Upload
set file = mySmartUpload.Files("file1")
Set MyConn = Server.CreateObject("ADODB.Connection")
Call OpenConnect(MyConn)
sql = "SELECT attach_data, title, idx, attach_type_id FROM c_attachment"
Set Rs = Server.CreateObject("ADODB.recordset")
Set rs.ActiveConnection = MyConn
rs.Source = sql
rs.CursorLocation = 3
rs.CursorType = 0
rs.LockType = 3
rs.Open sql
If not file.IsMissing Then 'Check for missing file
'Add the current file in database
Rs.AddNew
file.FileToField Rs.Fields("attach_data")
Rs("title") = "title test"
rs("idx") = "134774"
rs("attach_type_id") = 1
Rs.Update
rs.Close
set rs = nothing
End If
when i check the db table. attach_data is populated. now. when i try to read the image back, i keep getting "Response object: 007~ASP 0106~Type Mismatch~An unhandled data type was encountered." error on the BinaryWrite. please help!
Set MyConn = Server.CreateObject("ADODB.Connection")
Call OpenConnect(MyConn)
SQLQuery = "select attach_data,title from c_attachment where attach_id = 109"
Set RSList = MyConn.Execute(SQLQuery)
If RSList.EOF Then
blnImgExists = False
Else
FileData = RSList("attach_data")
blnImgExists = true
End If
if blnImgExists Then
Response.Clear
Response.ContentType = "image/jpeg"
Response.AddHeader "Content-disposition", "attachment; filename=image.jpg"
Response.BinaryWrite RSList("attach_data")
else
response.write "count not open"
end if

Images should be stored as BLOB data (Binary Large Object) in Oracle, not CLOB (Character Large Object).

Related

retrieve resultset from MSSQL stored procedure in classic asp

I'm not well versed in ASP, but that's what I've got to work with for the moment. I have a stored procedure that generates a resultset which i'd like to handle in classic ASP. I can see the resultset if I run the SP in SQL Management Studio with the same parameter so I know its working.
The stored procedure takes 1 parameter #part, i've testing with the following code and can see the SP is executed using SQL Profiler, but I get a '500 - Internal server error' returned from ASP instead of a resultset displayed.
How do correctly retrieve the resultset?
Dim fpart, objCommand, objRecordset
fpart = "SMF10320BRNU12"
Set objCommand = Server.CreateObject("ADODB.Command")
With objCommand
.ActiveConnection = db
.CommandText = "sp_movements"
.CommandType = 4
.CommandTimeout = 240
.Parameters.Append .CreateParameter("#part", 200, 1, 20)
.Parameters("#part") = fpart
Set objRecordset = .Execute
End With
for each x in objRecordset.Fields
Response.Write(x.name)
Response.Write(" = ")
Response.Write(x.value & "<br />")
next
Response.Write("<br />")
objRecordset.MoveNext
objRecordset.Close
Set objRecordset = nothing
objCommand.Close
Set objCommand = nothing
So I figured this out on my own. After digging though some logs I saw an error which I hadn't spotted previously:
Object_doesn't_support_this_property_or_method:_'Close'
Turns out I was incorrectly trying to close the command object: objCommand.Close
My working solution is:
Dim fpart, objCommand, objRecordset
fpart = "SMF10320BRNU12"
Set objCommand = Server.CreateObject("ADODB.Command")
With objCommand
.ActiveConnection = db
.CommandText = "sp_movements"
.CommandType = 4
.CommandTimeout = 240
.Parameters.Append .CreateParameter("#part", 200, 1, 20)
.Parameters("#part") = fpart
Set objRecordset = .Execute
End With
Do until objRecordset.EOF
for each x in objRecordset.Fields
Response.Write(x.name)
Response.Write(" = ")
Response.Write(x.value & "<br />")
next
Response.Write("<br />")
objRecordset.MoveNext
loop
objRecordset.Close
Set objRecordset = nothing
Set objCommand = nothing
Note:
This code also has a Do until loop around added to output all the rows from the recordset, but that wasn't strictly necessary to get something output on the page.
EDIT
Edited to reflect comments from Lankymart below, I did need to close the recordset.

Why does VBScript fail with a “Type mismatch" error?

I am experiencing difficulty with the following VBS
set conn = createobject("ADODB.Connection")
Conn.Provider = "ADsDSOObject"
Conn.Open "ADs Provider"
strQueryDL = "<LDAP://company.address.com/cn=address>;(&(objectCategory=person)(objectClass=user));distinguishedName,adspath;subtree"
set objCmd = createobject("ADODB.Command")
objCmd.ActiveConnection = Conn
objCmd.Properties("SearchScope") = 2 ' we want to search everything
objCmd.Properties("Page Size") = 500 ' and we want our records in lots of 500
objCmd.CommandText = strQueryDL
Set objRs = objCmd.Execute
While Not objRS.eof
wscript.echo objRS.Fields("distinguishedName")
' do something with objRS.Fields("distinguishedName")'
objRS.MoveNext
Wend
Please help me, I just started vbscripting and this was from an answer in this website.
wscript.echo objRS.Fields("distinguishedName")
The error was from the above line/code. How do I display out the field or convert it to display?
LDAP://company.address.com/cn=address is not a valid LDAP URL (see here). The search base must be a distinguished name, e.g.:
LDAP://company.address.com/cn=address,dc=address,dc=com
The distinguished name of the domain (dc=address,dc=com) can be obtained like this:
Set rootDSE = GetObject("LDAP://RootDSE")
WScript.Echo rootDSE.Get("defaultNamingContext")

How to get image from SQL Server

I have table called IMG and there are columns ID and Content that holds pictures.
How is it possible to get picture from there?
I googled for this problem and what all I got was vb.net, c# and php - mysql.
Maybe someone can say what is the best and easiest way to get picture (sample, copy/paste code, program)?
Thank you!
try something like this (from d_r_w's answer):
SqlDataAdapter dataAdapter = new SqlDataAdapter(
new SqlCommand("SELECT pic FROM imageTest WHERE pic_id = 1",
yourConnectionReference));
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
if (dataSet.Tables[0].Rows.Count == 1)
{
Byte[] data = new Byte[0];
data = (Byte[])(dataSet.Tables[0].Rows[0]["pic"]);
MemoryStream mem = new MemoryStream(data);
yourPictureBox.Image= Image.FromStream(mem);
}
Take alook at the complete answer
More options to do this:
Uploading / Downloading Pictures to / from a SQL Server
http://www.sqlusa.com/bestpractices/imageimportexport/
I found this post regards PHP but with MySQL(you need to change the connection to your server):
<?php
// image.php - by Hermawan Haryanto <hermawan#dmonster.com>
// Example PHP Script, demonstrating Storing Image in Database
// Detailed Information can be found at http://www.codewalkers.com
// database connection
$conn = mysql_connect("localhost", "user", "password")
OR DIE (mysql_error());
#mysql_select_db ("hermawan", $conn) OR DIE (mysql_error());
$sql = "SELECT * FROM image WHERE image_id=".$_GET["iid"];
$result = mysql_query ($sql, $conn);
if (mysql_num_rows ($result)>0) {
$row = #mysql_fetch_array ($result);
$image_type = $row["image_type"];
$image = $row["image"];
Header ("Content-type: $image_type");
print $image;
}
?>
after a lot of reading and work found the solution!
Here it is! Works 100%
Dim conn, sql, a, filename
Dim dir
dir = "c:\images\" //saves files into this directory
Dim fileObj
Set fileObj = CreateObject("Scripting.FileSystemObject")
Set conn = CreateObject("ADODB.Connection")
Dim strStream
Set strStream = CreateObject("ADODB.Stream")
Dim rstRecordset
Set rstRecordset = CreateObject("ADODB.Recordset")
conn.Open "Provider=SQLOLEDB;Data Source=yourserver;Integrated Security = SSPI","username","password"
rstRecordset.Open "Select xxx, yyy, zzz from table (nolock) where xxx = '' order by xxx desc", conn ', adOpenKeyset, adLockOptimistic
Set fso = CreateObject("Scripting.FileSystemObject")
While Not rstRecordset.EOF
filename = rstRecordset.Fields(0)
er = 0
Do
er = er+1
Loop While (fso.FileExists(dir & filename & "_" & er & ".JPG"))
filename = dir & filename & "_" & er & ".JPG"
strStream.Type = 1
strStream.Open
strStream.Write rstRecordset.Fields(2).Value
strStream.SaveToFile filename
strStream.Close
rstRecordset.MoveNext
Wend
Here it is!

How to add picture into database?

I have created a table mypics that contains one column of BLOB datatype.
Now I need to implement a vb6 code to Select/Insert/Update data in this table, but I don`t know how to deal with the BLOB column...
SQL> desc mypics
Name Null? Type
PID NOT NULL NUMBER(38)
PNAME CHAR(10)
IMAGE BLOB
Please help
Here is some example code to get you started. Assume a table named tblImages with 3 fields.
Field Data Type Size
Picture Image
ID Int 4
To add an image from a file on disk to the database
Set strStream = New ADODB.Stream
strStream.Type = adTypeBinary
strStream.Open
strStream.LoadFromFile strFileName
strSQL = "SELECT ID, Picture FROM tblImages"
Set rs = New ADODB.Recordset
With rs
.ActiveConnection = cn
.Source = strSQL
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Open
End With
rs.AddNew
rs.Fields("ID").Value = ID
rs.Fields("Picture").Value = strStream.Read
rs.Update
rs.Close
Set rs = Nothing
To extract the file from database to a disk file :
strSQL = "SELECT Picture FROM tblImages WHERE ID = " & ID
Set rs = New ADODB.Recordset
With rs
.ActiveConnection = cn
.Source = strSQL
.Open
End With
If Not (rs.BOF And rs.EOF) Then
Set strStream = New ADODB.Stream
strStream.Type = adTypeBinary
strStream.Open
strStream.Write rs!Picture
strStream.SaveToFile TempPath, adSaveCreateOverWrite
strStream.Close
Set strStream = Nothing
End If
rs.Close
Set rs = Nothing
I hope this helps.

How to save picture in BLOB format?

I did code for procedure that prompts for a .jpeg file, converts that file to a Byte array, and saves the Byte Array to the table using the Append chunk method.
Another procedure retrieves the picture image from the table using the GetChunk method, converts the data to a file and displays that file in the Picture box.
Now, my question is that how do I save that image displayed in picture box into the database, so that I can perform operations like: add/update etc.
I did something like this way:
Private Sub CmdSave_Click()
if(cmbRNO=" ") then
sql = "INSERT INTO STUDENT_RECORD_DATABASE(ROLLNO,PICS)"
sql = sql + "VALUES(" & RNo & ","& picture1.picture &")"
Set RES = CON.Execute(sql)
Else
sql = "UPDATE STUDENT_RECORD_DATABASE SET "
sql = sql + "ROLLNO= " & Val(CmbRNO) & ","
sql = sql + "PICS=" & Picture1.Picture & " "
sql = sql + "WHERE ROLLNO= " & Val(CmbRNO) & ""
Set RES = CON.Execute(sql)
End If
End Sub
<code for appendchunk method>
Public Sub Command1_Click()
Dim PictBmp As String
Dim ByteData() As Byte 'Byte array for Blob data.
Dim SourceFile As Integer
' Open the BlobTable table.
strSQL = "Select ID, DOC from LOB_TABLE WHERE ID = 1"
Set Rs = New ADODB.Recordset
Rs.CursorType = adOpenKeyset
Rs.LockType = adLockOptimistic
Rs.Open strSQL, Cn
' Retrieve the picture and update the record.
CommonDialog1.Filter = "(*.jpeg)|*.jpeg"
CommonDialog1.ShowOpen
PictBmp = CommonDialog1.FileName
' Save Picture image to the table column.
SourceFile = FreeFile
Open PictBmp For Binary Access Read As SourceFile
FileLength = LOF(SourceFile) ' Get the length of the file.
If FileLength = 0 Then
Close SourceFile
MsgBox PictBmp & " empty or not found."
Exit Sub
Else
Numblocks = FileLength / BlockSize
LeftOver = FileLength Mod BlockSize
ReDim ByteData(LeftOver)
Get SourceFile, , ByteData()
Rs(1).AppendChunk ByteData()
ReDim ByteData(BlockSize)
For i = 1 To Numblocks
Get SourceFile, , ByteData()
Rs(1).AppendChunk ByteData()
Next i
Rs.Update 'Commit the new data.
Close SourceFile
End If
End Sub
While trying to save image to specific record, run-time error occurs:
inconsistent datatype,expected BLOB got number
Where as:
?sql
UPDATE STUDENT_RECORD_DATABASE SET ROLLNO= 132,PICS=688195876 WHERE ROLLNO= 132

Resources