vijay

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



hi...

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..
GO
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
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


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

In vb.net 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


 Try
'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
                    cmd.Parameters.Add(ImageName)


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


    End Sub

Hope this helps to u.....

0 comments:

Post a Comment