Question upload doc/execl/pdf/huge file in to db

skaswani

Member
Joined
Oct 5, 2008
Messages
20
Programming Experience
Beginner
vb.net, sql server 2005

HEllo All

i have a code which allow me to upload small files , but doies'nt allow me to upload DOC/PDF/Tiff Files to database

i am getting
Out of memory. error

kindly advise

VB.NET:
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Public Class Form1
    Private mImageFile As Image
    Private mImageFilePath As String
    Private Sub btnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFind.Click
        OpenFileDialog1.Title = "Set Image File"
        OpenFileDialog1.Filter = "Bitmap Files|*.bmp|Gif Files|*.gif|JPEG Files|*.jpg|PDF Files|*.pdf|DOC Files|*.doc"
        OpenFileDialog1.DefaultExt = "bmp"
        OpenFileDialog1.FilterIndex = 1
        OpenFileDialog1.FileName = ""
        OpenFileDialog1.ShowDialog()
        Dim sFilePath As String
        sFilePath = OpenFileDialog1.FileName
        If sFilePath = "" Then Exit Sub

        If System.IO.File.Exists(sFilePath) = False Then

            Exit Sub

        Else

            txtImageFile.Text = sFilePath
            mImageFilePath = sFilePath

        End If

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try

            If (Me.txtImageFile.Text = String.Empty Or Me.txtTitle.Text = String.Empty) Then

                MessageBox.Show("Complete both form fields prior to submitting", "Missing Values", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

                Exit Sub

            End If

        Catch ex As Exception

            MessageBox.Show(ex.Message.ToString(), "File Test Error")

        End Try



        Dim fs As FileStream = New FileStream(mImageFilePath.ToString(), FileMode.Open)


        Dim img As Byte() = New Byte(fs.Length) {}

        fs.Read(img, 0, fs.Length)

        fs.Close()



        mImageFile = Image.FromFile(mImageFilePath.ToString())
        Dim imgHeight As Integer = mImageFile.Height
        Dim imgWidth As Integer = mImageFile.Width
        Dim imgLength As Integer = mImageFile.PropertyItems.Length
        Dim imgType As String = Path.GetExtension(mImageFilePath)
        mImageFile = Nothing


        Dim strConnect As String

        strConnect = "Data Source=sajjad-laptop;Initial Catalog=master;User ID=sa ; password=sajjad"

        Dim conn As SqlConnection = New SqlConnection(strConnect)



        Dim sSQL As String = "INSERT INTO store_image(ImageContent, ImageTitle, ImageType, ImageHeight, ImageWidth) VALUES(  @pic, @title, @itype, @iheight, @iwidth  )"



        Dim cmd As SqlCommand = New SqlCommand(sSQL, conn)



        ' image content

        Dim pic As SqlParameter = New SqlParameter("@pic", SqlDbType.Image)

        pic.Value = img

        cmd.Parameters.Add(pic)



        ' title

        Dim title As SqlParameter = New SqlParameter("@title", System.Data.SqlDbType.VarChar, 50)

        title.Value = txtTitle.Text.ToString()

        cmd.Parameters.Add(title)



        ' type

        Dim itype As SqlParameter = New SqlParameter("@itype", System.Data.SqlDbType.Char, 4)

        itype.Value = imgType.ToString()

        cmd.Parameters.Add(itype)



        ' height

        Dim iheight As SqlParameter = New SqlParameter("@iheight", System.Data.SqlDbType.Int)

        iheight.Value = imgHeight

        cmd.Parameters.Add(iheight)



        ' width

        Dim iwidth As SqlParameter = New SqlParameter("@iwidth", System.Data.SqlDbType.Int)

        iwidth.Value = imgWidth

        cmd.Parameters.Add(iwidth)



        Try

            conn.Open()

            cmd.ExecuteNonQuery()

            conn.Close()

            MessageBox.Show("Query executed.", "Image Load")

        Catch ex As Exception

            MessageBox.Show(ex.Message.ToString(), "Data Error")

            Exit Sub

        End Try


    End Sub
End Class



thanks
 
Last edited:
error in attachment for better understanding

thanks
 

Attachments

  • error.JPG
    error.JPG
    147 KB · Views: 54
its working fine with jpg pic/image file, i just uploaded 2 mb file .. it worked,

so, i just want to know can i download that pic on harddisk//
i mean.. if i search some record and then want to download related image..
pls help me
regards
 
Of course it doesn't work for DOC or PDF files. You can't call Image.FromFile unless the file actually IS an image file. DOC and PDF files do not contain images so they cannot be used to create Image objects.

The Image object is not really important. All you need to do is get the raw binary data from the file and save that, which you can get for any type of file by calling IO.File.ReadAllBytes. That will create a Byte array that you can save directly to a database. When you get the data back from the database you can call IO.File.WriteAllBytes to do the reverse.

Also, this code is wrong:
VB.NET:
        OpenFileDialog1.Title = "Set Image File"
        OpenFileDialog1.Filter = "Bitmap Files|*.bmp|Gif Files|*.gif|JPEG Files|*.jpg|PDF Files|*.pdf|DOC Files|*.doc"
        OpenFileDialog1.DefaultExt = "bmp"
        OpenFileDialog1.FilterIndex = 1
        OpenFileDialog1.FileName = ""
        OpenFileDialog1.ShowDialog()
        Dim sFilePath As String
        sFilePath = OpenFileDialog1.FileName
        If sFilePath = "" Then Exit Sub

        If System.IO.File.Exists(sFilePath) = False Then

            Exit Sub

        Else

            txtImageFile.Text = sFilePath
            mImageFilePath = sFilePath

        End If
For a start, assuming that this is the only place the OFD is being used, most of those property values should be set in the designer.

Second, you should be setting CheckFileExists to True so the user cannot select a non-existent file. That way, there's no need for you to write code to check if the file exists.

Finally, you should ONLY be processing the file if the user clicks OK:
VB.NET:
OpenFileDialog1.FileName = ""

If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
    mImageFilePath = OpenFileDialog1.FileName
    txtImageFile.Text = mImageFilePath
End If
That should be all the code you need.
 
Dear Friend
can you help me with this code?


i am trying to Show Picture store id db and then export it to image file,

Please assist me in this code


VB.NET:
 Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Dim con As SqlConnection
        con = New SqlConnection("Data Source=SKASWANI-PC\SQLEXPRESS;Initial Catalog=master;Integrated Security=True")
        Dim selectSql As String
        Dim cmd As SqlCommand
        Dim storedImage As Byte()
        Dim newImage As Image
        ' Dim stream As MemoryStream


        selectSql = "select imagesrc from imageprocess where img_id=1"
        cmd = New SqlCommand(selectSql, con)
        con.Open()
        storedImage = cmd.ExecuteScalar

        Using stream = New MemoryStream(storedImage)
            newImage = Image.FromStream(stream)
        End Using

        PictureBox1.Image = newImage

    End Sub

error i am getting is

Parameter is not valid. at line :
newImage = Image.FromStream(stream)




regards
 
saving image like this

VB.NET:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        filDlg = New OpenFileDialog()
        filDlg.Filter = "All Pictures|*.bmp;*.gif;*.jpg|Bitmaps|*.bmp|GIFs|*.gif|JPEGs|*.jpg"
        dlg = filDlg.ShowDialog()


        If (dlg = DialogResult.Cancel) Then
            Return
        End If
        '  PictureBox1.Image new as  New Bitmap(filDlg.FileName)

        fName = filDlg.FileName.ToString()

        itx = fName.LastIndexOf("\\")
        fName = fName.Substring(itx + 1)
        ms = New MemoryStream()

        'PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)
        arrImage = ms.GetBuffer()
        ms.Close()
        Str = "insert into imageprocess (imagename,imagesrc) values (@imagename,@imagesrc)"

        Dim con As SqlConnection
        con = New SqlConnection("Data Source=SKASWANI-PC\SQLEXPRESS;Initial Catalog=master;Integrated Security=True")
        Dim cmd As SqlCommand
        cmd = New SqlCommand(str, con)
       

        cmd.Parameters.Add("@imagesrc", SqlDbType.Image).Value = arrImage
        cmd.Parameters.Add("@imagename", SqlDbType.VarChar, 50).Value = fName
        con.Open()
        cmd.ExecuteNonQuery()
        MessageBox.Show("Image saved successfully", "Image Process", MessageBoxButtons.OK, MessageBoxIcon.Information)


    End Sub


thanks
 
Well you've got a bit of a problem then. You aren't actually saving any data. You create a MemoryStream and immediately call its GetBuffer method. You haven't written any data to the stream so there's no data to read, so your Byte array is empty. Test the Length property of arrImage and you'll see that.

If you want to read the data from the MemoryStream then you have to write it to the MemoryStream first. The line that would have done that is commented out, probably because it wouldn't have worked anyway because you never actually create an Image object to call Save on.

If you're not intending to display the image to the user then why not just do what I suggested earlier and call File.ReadAllBytes to get your data? If you do intend to display the image then you have to create an Image to display, which you can then save to your MemoryStream.
 
actully last night i had 5 hours of web surffing on this topic,

i got code related to asp.net but not vb .net, i have no fair idea that does this code actully write anything to database or not,

finnally i got some code from net which were actully in c sharp, i spend many hours to convert into vb.net :eek: , but as u said still not worked

wht i want to do,

actully i want to use this to store images for 2 purpose

1) store picture/snap of the user to db which actully display on my form, i dont have to download,

2) i need up save user request which i need to actully download on request not display


did u get now a fair ide awhat i am trying to do and why i am bit confused.

can u help me in this,

suggest me what i do,

can i p.m. u if u allow,

Regards
 
So basically you're saying that you want the user to select an image file and you will display it and save it to the database. The user can then retrieve the image from that database and save it to a file again. Is that a fair assessment?
 
no no... let me give u a realistic picture

i might have a table user, which might have columns as

user_master (table)
==============
userno int, (pk)
name varchar,
address varchar,
deptno int,

user_image (table)
==============

userno int, (fk of user_master)
user_snap image,
user_form image,



1) user_snap need to be save and display From
2) user_form need to be downloaded if clicked on download button


on form , i have while adding records,

i'll upload 2 images 1st snap and 2nd user_form

on inquiry/display form user_snap will be shown as picture on win form and their will be a link/ button to download his /her user_form


make sence??

thanks
 
i don't see how it's any different to what has already been posted.. a snap is just a small version (a thumbnail) of the big picture, yes?

Try using File.ReadAllBytes to read the image bytes from the file, rather than putting it ina picture box, and then a memory stream, and then a buffer, and then forgetting to do anything with it.

Upload the bytes array into the DB for both snapshot and main. I'm sure there will be lots of stuff on the web about putting binary data into a db. I've always thought it a dumb idea, and preferred to store them on disk, and put the path to the image in the db, but i can see how it doesnt work in all situations
 
Back
Top