welcome Netizen

Share Your Knowledge.It is a way to achieve immortality

Sunday, February 6, 2011

Upload a Image or File into Database in ASP.NET using VB coding


In previous articles we have seen about uploading files into folder..This articles to update a files into  database...
For that you have to add following items in design side..
1) File upload
2)1 Button
3) text box
4) Label

Before in SQL you have to create a table like this..
CREATE TABLE [dbo].[upload](
[fileid] [int] IDENTITY(1,1) NOT NULL,
[ImageName] [varchar](max) COLLATE SQL_Latin1_General_CP1_CS_AS NULL,
[Image] [image] NULL

Follow the server side coding....
In submit button you have to add the following codes.....

In file uploading has one important property  HTTPPOSTEDFILE, by using this property we can easily get the file upload details
like file length,file content type and file name.....Also we can easily check  file extension..For an example if we want to upload only gif image
means by using content type we can check the file type...After checking we can upload the file into database

'Checking the file in fileupload
            If FileUpload1.HasFile Then

                Dim imageSize As Byte()
                imageSize = New Byte(FileUpload1.PostedFile.ContentLength - 1) {}

                Dim postfile As HttpPostedFile = FileUpload1.PostedFile()

                postfile.InputStream.Read(imageSize, 0, CInt(FileUpload1.PostedFile.ContentLength))

                ' Create SQL Connection 
                Dim con As New SqlConnection()
                con.ConnectionString = ConfigurationManager.ConnectionStrings("Con").ConnectionString

                ' Create SQL Command 
'Checking file type
                If postfile.ContentType.ToLower() = "image/gif" Then

                    Dim cmd As New SqlCommand()
                    cmd.CommandText = "INSERT INTO upload(ImageName,Image) VALUES (@ImageName,@Image)"
                    cmd.CommandType = CommandType.Text
                    cmd.Connection = con
                    Dim ImageName As New SqlParameter("@ImageName", SqlDbType.VarChar, 50)
                    ImageName.Value = TextBox1.Text.ToString

                    Dim imagelenth As New SqlParameter("@Image", SqlDbType.Image, imageSize.Length)
                    imagelenth.Value = imageSize
                    Dim result As Integer = cmd.ExecuteNonQuery()
                    Label1.Text = "Its not a gif image"
                End If
                Label1.Text = "please select the file to uplaod"
            End If
        Catch ex As Exception
        End Try

    End Sub

Hope this helps to u.....


Post a Comment