Click here to Skip to main content
15,884,237 members
Please Sign up or sign in to vote.
1.24/5 (3 votes)
See more:
I have a images folder in my project now i want to save those images in a database so that they can display on a Gridview.
Posted
Comments
Thanks7872 1-Sep-15 5:00am    
And your question is?

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);

//to get the files that are present in that folder.
List <<string>> directoryFiles = Directory.GetFiles(HttpContext.Current.Server.MapPath("~/uploads")).ToList();

//loop through each file and save it in the database.
foreach (string file in directoryFiles)
{
using (FileStream fs = new FileStream(file , FileMode.Open, FileAccess.Read))
{
byte[] imageData = new Byte[fs.Length];
fs.Read(imageData, 0, (int)fs.Length);

conn.Open();
SqlCommand cmd = new SqlCommand("Insert into Album (Album_Name,Album_Date,Album_Image) values(@name,@date,@image)", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@date", date);
cmd.Parameters.AddWithValue("@image", imageData);
cmd.ExecuteNonQuery();
conn.Close();
}
}
 
Share this answer
 
v2
Below are the steps read all the images from a specified folder using stored procedure.

1). Create Table
SQL
GO

CREATE TABLE [dbo].[TBLImages] (
    [ImageId] [int] IDENTITY (1, 1) NOT NULL ,
    [OriginalPath] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    [ImageData] [image] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO


2). Create Stored Procedure


SQL
Create procedure SPCopyImagesToTable @filepath varchar(500), 
	@pattern varchar(100), @TableName varchar(128)
as
BEGIN
set quoted_identifier off
declare @query varchar(1000)
declare @max1 int
declare @count1 int
Declare @filename varchar(100)
set @count1 =0
create table #x (name varchar(200))
set @query ='master.dbo.xp_cmdshell "dir '+@filepath+@pattern +' /b"'
insert #x exec (@query)
delete from #x where name is NULL
select identity(int,1,1) as ID, name into #y from #x 
drop table #x
set @max1 = (select max(ID) from #y)
--print @max1
--print @count1
While @count1 <= @max1
begin
set @count1=@count1+1
set @filename = (select name from #y where [id] = @count1)

INSERT INTO [dbo].[ImageInsert]([OriginalPath], [ImageData])
Select @Filepath+@Filename,(SELECT * FROM OPENROWSET(BULK @Filepath+@Filename, SINGLE_BLOB))AS Images

end

drop table #y

END


3). Execute Store procedure.

SQL
Exec SPCopyImagesToTable 'd:\images\', '*.jpg', 'TBLImages'
 
Share this answer
 
For save image in database u have to take datatype as image.
 
Share this answer
 
Comments
Arasappan 1-Sep-15 7:17am    
its only path.. we can take image path as nvarchar also..

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