Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
1.40/5 (2 votes)
hi friend

i need to store and display that image in the same page ....the key was empid . Its datatype was varchar(10)..

my db is

create table employee
(
empid varchar(10) identity not null,
EmpName varchar(20) not null,
EmpImage image not null,
)

My coding is

Default.aspx

Imports System.Data.SqlClient

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim connection As New SqlConnection
Try
Dim img As FileUpload = CType(imgUpload, FileUpload)
Dim imgByte As Byte() = Nothing
If img.HasFile AndAlso Not img.PostedFile Is Nothing Then
'To create a PostedFile
Dim File As HttpPostedFile = imgUpload.PostedFile
'Create byte Array with file len
imgByte = New Byte(File.ContentLength - 1) {}
'force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength)
End If
' Insert the employee name and image into db
Dim conn As String = ConfigurationManager.ConnectionStrings("Data Source=BOSS\SQLEXPRESS;Initial Catalog=simple;User ID=sa").ConnectionString
connection = New SqlConnection(conn)
connection.Open()
Dim sql As String = "INSERT INTO EmpDetails(empid,empname,empimg) VALUES(@Empid,@Empname, @Empimage) SELECT @@IDENTITY"
Dim cmd As SqlCommand = New SqlCommand(sql, connection)
cmd.Parameters.AddWithValue("@Empid", EmpNumber.Text.Trim())
cmd.Parameters.AddWithValue("@Empname", txtEName.Text.Trim())
cmd.Parameters.AddWithValue("@Empimage", imgByte)
Dim id As String = Convert.ToInt32(cmd.ExecuteScalar())
lblResult.Text = String.Format("Employee ID is {0}", id)

' Display the image from the database
Image1.ImageUrl = "~/ShowImage.ashx?id=" & id
Catch
lblResult.Text = "There was an error"
Finally
connection.Close()
End Try
End Sub
End Class


ShowImage.ashx

<%@ WebHandler Language="vb" Class="ShowImage" %>

Imports System
Imports System.Configuration
Imports System.Web
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient

Public Class ShowImage
Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim empno As String
If Not context.Request.QueryString("id") Is Nothing Then
empno = Convert.ToInt32(context.Request.QueryString("id"))
Else
Throw New ArgumentException("No parameter specified")
End If

context.Response.ContentType = "image/jpeg"
Dim strm As Stream = ShowEmpImage(empno)
Dim buffer As Byte() = New Byte(4095) {}
Dim byteSeq As Integer = strm.Read(buffer, 0, 4096)

Do While byteSeq > 0
context.Response.OutputStream.Write(buffer, 0, byteSeq)
byteSeq = strm.Read(buffer, 0, 4096)
Loop
'context.Response.BinaryWrite(buffer);
End Sub

Public Function ShowEmpImage(ByVal empno As String) As Stream
Dim conn As String = ConfigurationManager.ConnectionStrings("Data Source=BOSS\SQLEXPRESS;Initial Catalog=simple;User ID=sa").ConnectionString
Dim connection As SqlConnection = New SqlConnection(conn)
Dim sql As String = "SELECT empimg FROM EmpDetails WHERE Empid = @ID"
Dim cmd As SqlCommand = New SqlCommand(sql, connection)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("@ID", empno)
connection.Open()
Dim img As Object = cmd.ExecuteScalar()
Try
Return New MemoryStream(CType(img, Byte()))
Catch
Return Nothing
Finally
connection.Close()
End Try
End Function

Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property


End Class

I include all my coding friend pls Execute and correct the Error

Very very thanks in advance..........
Posted
Updated 9-Jul-13 18:45pm
v4
Comments
raj ch 1-Jul-13 7:32am    
use blob field in database

Create Table.....

SQL
CREATE DATABASE [Employee]
GO
USE [Employee]
GO
CREATE TABLE EmpDetails
(
empid int IDENTITY NOT NULL,
empname varchar(20),
empimg image
)








C#
C#
protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SqlConnection connection = null;
        try
        {
            FileUpload img = (FileUpload)imgUpload;
            Byte[] imgByte = null;
            if (img.HasFile && img.PostedFile != null)
            {
                //To create a PostedFile
                HttpPostedFile File = imgUpload.PostedFile;
                //Create byte Array with file len
                imgByte = new Byte[File.ContentLength];
                //force the control to load data in array
                File.InputStream.Read(imgByte, 0, File.ContentLength);
            }
            // Insert the employee name and image into db
string conn = ConfigurationManager.ConnectionStrings ["EmployeeConnString"].ConnectionString;
            connection = new SqlConnection(conn);
 
            connection.Open();
string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY";
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
            cmd.Parameters.AddWithValue("@eimg", imgByte);
            int id = Convert.ToInt32(cmd.ExecuteScalar());
            lblResult.Text = String.Format("Employee ID is {0}", id);
        }
        catch
        {
            lblResult.Text = "There was an error";
        }
        finally
        {
            connection.Close();
        }
 
    }





for VB.NET....


VB
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        Dim connection As SqlConnection = Nothing
        Try
            Dim img As FileUpload = CType(imgUpload, FileUpload)
            Dim imgByte As Byte() = Nothing
            If img.HasFile AndAlso Not img.PostedFile Is Nothing Then
                'To create a PostedFile
                Dim File As HttpPostedFile = imgUpload.PostedFile
                'Create byte Array with file len
                imgByte = New Byte(File.ContentLength - 1) {}
                'force the control to load data in array
                File.InputStream.Read(imgByte, 0, File.ContentLength)
            End If
            ' Insert the employee name and image into db
            Dim conn As String = ConfigurationManager.ConnectionStrings("EmployeeConnString").ConnectionString
            connection = New SqlConnection(conn)

            connection.Open()
            Dim sql As String = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY"
            Dim cmd As SqlCommand = New SqlCommand(sql, connection)
            cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim())
            cmd.Parameters.AddWithValue("@eimg", imgByte)
            Dim id As Integer = Convert.ToInt32(cmd.ExecuteScalar())
            lblResult.Text = String.Format("Employee ID is {0}", id)
        Catch
            lblResult.Text = "There was an error"
        Finally
            connection.Close()
        End Try
    End Sub
 
Share this answer
 
Comments
Sureshfrompalladam 3-Jul-13 0:17am    
dear nirav prabtani friend

thanks for ur reply but i need of varchar datatype i modified my question please see that
Nirav Prabtani 3-Jul-13 0:35am    
may i know,

now what is the trouble you face??
Member 9579525 3-Jul-13 0:31am    
you can save image in binary format and display it..the datatype is varbinary for image
Nirav Prabtani 3-Jul-13 8:27am    
ya but what kind of error is there???
Nirav Prabtani 3-Jul-13 8:51am    
check by break point and u will get error...: )
thank u friend u tried for me ...

i didnt store into the database so only i got error now i solved that .....

my coding

Imports System.Data.SqlClient
Imports System.Data

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim mConnection As SqlConnection = Nothing
Try
Dim img As FileUpload = CType(imgUpload, FileUpload)
Dim imgByte As Byte() = Nothing
If img.HasFile AndAlso Not img.PostedFile Is Nothing Then
'To create a PostedFile
Dim File As HttpPostedFile = imgUpload.PostedFile
'Create byte Array with file len
imgByte = New Byte(File.ContentLength - 1) {}
'force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength)
End If
Insert the employee name and image into db
Dim conn As String

Dim conn As String = ConfigurationManager.ConnectionStrings("EmployeeConnString").ConnectionString
conn = "Data Source=BOSS\SQLEXPRESS;Initial Catalog=simple;User ID=sa"
connection = New SqlConnection(conn)
connection.Open()
Dim sql As String = "INSERT INTO EmpDetails (Empid,Empname,Empimage)VALUES (@Empid,@Empname, @Empimage) SELECT @@IDENTITY"
Dim cmd As SqlCommand = New SqlCommand(sql, connection)
cmd.Parameters.AddWithValue("@Empid", EmpNumber.Text.Trim())
cmd.Parameters.AddWithValue("@Empname", txtEName.Text.Trim())
cmd.Parameters.AddWithValue("@Empimage", imgByte)
mCommand.ExecuteNonQuery()

Dim id As String = EmpNumber.Text
lblResult.Text = String.Format("Employee ID is {0}", id)


Image1.ImageUrl = "~/ShowImage.ashx?id=" & id

Catch
lblResult.Text = "There was an error"
Finally
mConnection.Close()
End Try
End Sub


the showImage coding was same as above

thanks & regards

Suresh
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900