Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

how to save images into folder and images path in database and display images from folder in gridview based on images path in database using asp.net

Mar 3, 2011
Introduction:

In this article I will explain how to insert images into our project folder and display the images from folder in gridview based on images path in database using asp.net.

Description:
  

In my previous article I explained clearly how to insert images into database and display images from database into gridview. Now I will explain how to insert images into our project folder and insert images path into database and display images in gridview from images folder based on Images path in database. For that first create new website after that right click on your website and add new folder and give name as Images because here I used same name for my sample if you want to change folder name you need to change the images folder name in your code behind also
first design table in your database like this to save images path in database.

Column Name
Data Type
Allow Nulls
ID
int(set identity property=true)
No
ImageName
varchar(50)
Yes
ImagePath
nvarchar(max)
Yes
Now Design your aspx page like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Save Images In Folder and Display Images in Gridview from folder</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileuploadimages" runat="server" />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</div>
<div>
<asp:GridView runat="server" ID="gvImages" AutoGenerateColumns="false" DataSourceID="sqldataImages" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8" >
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="ImageName" HeaderText="Image Name" />
<asp:ImageField HeaderText="Image" DataImageUrlField="ImagePath" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sqldataImages" runat="server"  ConnectionString="<%$ConnectionStrings:dbconnection %>"
SelectCommand="select * from ImagesPath" >
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
After completion of aspx page design add using System.IO; reference in codebehind and write the following code


protected void btnSubmit_Click(object sender, EventArgs e)
{
//Get Filename from fileupload control
string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);
//Save images into Images folder
fileuploadimages.SaveAs(Server.MapPath("Images/"+filename));
//Getting dbconnection from web.config connectionstring
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
//Open the database connection
con.Open();
//Query to insert images path and name into database
SqlCommand cmd = new SqlCommand("Insert into ImagesPath(ImageName,ImagePath) values(@ImageName,@ImagePath)", con);
//Passing parameters to query
cmd.Parameters.AddWithValue("@ImageName", filename);
cmd.Parameters.AddWithValue("@ImagePath", "Images/" + filename);
cmd.ExecuteNonQuery();
//Close dbconnection
con.Close();
Response.Redirect("~/Default.aspx");
}
After that set your database connection in web.config like this because we are using this connection in our sqldatasource to get the data from database


<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings >


Demo

If you want to validate uploaded file format (.jpeg, .gif, .gif) check this link how to validate file type in uploaded control

Download sample code attached

 

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

122 comments :

Anonymous said...

Hi,
Your post is really excellent and this is what i am looking for and one problem is that when we enter the Data type in the database field for Image Name it gives me an error stating that Operand type clash: nvarchar is incompatible with image so can you please attch you database so that it helps me a lot.
Thank you.

Suresh Dasari said...

hi,
thanks for your suggestion i will try to attach the db file also here the problem is your sending the image data to ImageName field(varchar datatype)that's why that is showing exception please send the data in correct way image name to ImageName field and image data to Image field it will work for you

Anonymous said...

Hi suresh,
Thanks for your reply and as soon as we upload and if we run the code once again it is showing all the images which we have previously uploaded and there is any other possibility to remove them as soon as we run for the second time.

Anonymous said...

And suresh I would like to have the same with resizing the images while uploading.Can you include in this part or can you give me an example based on that with lightbox effect as you have described.

adi said...

hi suresh this is adhi
in this post i got an error like
network instance error
please solve and tell me

Suresh Dasari said...

hi check these posts one is to resize the image without losing quality of image
http://aspdotnet-suresh.blogspot.com/2011/05/how-to-resize-size-image-without-losing.html

and second one is generate thumbnails during upload images using asp.net
http://aspdotnet-suresh.blogspot.com/2011/05/how-to-create-or-generate-thumbnails.html

Suresh Dasari said...

hi adhi,
that problem with your database connection check you gave correct database path or not if you gave correct database path check whether you have permission for that database or not

Rpaxis said...

The post is written in very a good manner and it entails many useful information for me. Awesome blog about long island database design. Thanks for sharing.

Anonymous said...

hi.. error in Operand type clash: nvarchar is incompatible with image

Anonymous said...

hi.. i'm siva error in Operand type clash: nvarchar is incompatible with image

subbu said...

Hi, suresh i have downloaded and run this code followed by changing the db connection tags as per my sysystem. but here is an error
"Operand type clash: nvarchar is incompatible with image"
give a solution for it.

Dheeraj said...

Hi Suresh,
I just want to know how to use image uploader control in WYSIWYG Editor and display uploaded image in WYSIWYG Editor design view.

Darrjus said...

Hi Mr Suresh its nice tutorial but some people already wrote inavalible nvarchar I try this in

//* SqlParameter ImagePathParam = new SqlParameter("@ImagePath", SqlDbType.Image);
ImagePathParam.Value = DBNull.Value;
cmd.Parameters.Add(ImagePathParam); *//

This code eliminates errors in nvarchar but path in database is NULL
So if you want see pictures in GridView and Path in Database. You should created yours database ImagePath = varchar(150) (instead of image) and its done!
PS Its should be helpfull in other people looking for this problem.
Greet

Anonymous said...

Hi. This is a good tutorial. But may I know how to I let an user who had logged in his/her own account and upload the picture and the picture is link to her/her own username.

Deepal Brahmbhatt said...

Haiee Suresh

your article is a superb but there is one error in the database in the database there in ImagePath we should to give a database type is nvarchar(max). after it it will work smoothly & give a new look of Gridview. otherwise Its seriously helpful to me ... thanks a lot ... :)

KAmlesh said...

Could any one please tell me how to retrieve and save images into the server from Windows Application using Sql Server.

Anonymous said...

how to send feedback through email in asp.netcode

bhawna said...

hii can u teel me he same procedure when using oracle database

Anonymous said...

thanks for sharing
http://soft-engineering.blogspot.com

Matty Sko said...

Exellent, clean and simple, what good code should be!

sachin said...

very very thanks...........
m person who give first time comment to your tutorial because i really like it
.
.
.
.
.
..
thanks again

mansoorali said...

coming same error like "Operand type clash: nvarchar is incompatible with image".How to solve this problem,pls help me

Suresh Dasari said...

@TIP-MANSHAF
that problem because of ImagePath. Please change ImagePath Datatype to nvarchar(max) in your table and try it will work for you.

Suresh Dasari said...

@TIP-MANSHAF
that problem because of ImagePath. Please change ImagePath Datatype to nvarchar(max) in your table and try it will work for you.

Anonymous said...

hi

i have to display an image into the page which is fetch from the any specific folder how it done?

Amar Prasad said...

Hi sir,
i have 3 buttons Add/Update/Delete in my Grid View,..Plz, sir can u say me how to ADD/UPDATE/DELETE images in Grid View...

Plz,mail me on tech.amarprasad@gmail.com

Amar Prasad said...

Hi sir,
i have 3 buttons Add/Update/Delete in my Grid View,..Plz, sir can u say me how to ADD/UPDATE/DELETE images in Grid View...

Plz,mail me on tech.amarprasad@gmail.com

kunal said...

hi i have two tables named Data and Image in which both have a common column that is File_Name. I have to perform Insert, Update, Delete operation in both table at same time that means if i clik save button then data will save in both table by one button click event and how i fetch data in gridview from both table

kunal said...

Hi suresh i run ur application by making Imagepath table but it only retrieve image name and image path in gridview and it doesn't save image in image folder nor it doesn't show image in gridview. it show image path at the place of image

Suresh Dasari said...

@kunal..
this sample working perfectly i hope you did mistake in your code check whether you created Images folder in your application or not to save images

cory church said...

Really great tutorial - best I've seen for newbies like me. I believe I have something wrong with the web.config connectionstring you provided. Am I supposed to edit that to fit my environment? If so, what do I edit? I am getting the below message when I try to view the page in the browser:

Server Error in '/' Application.
--------------------------------------------------------------------------------

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

Suresh Dasari said...

@cory church
change connectionString in web.config file. Here i given my database connection instead of my dbconnection give your database connection

aluson said...

Hisir;
sir post is really excellent and this is what i am looking for and one problem is that when i run it it occur



Compiler Error Message: CS1061: 'ASP.default_aspx' does not contain a definition for 'gvImages_SelectedIndexChanged' and no extension method 'gvImages_SelectedIndexChanged' accepting a first argument of type 'ASP.default_aspx' could be found (are you missing a using directive or an assembly reference?)

so plz hlep me sir

Suresh Dasari said...

@aluson,
you define gvImages_SelectedIndexChanged this event in aspx page but that code doesnot exists in code behind because of that your getting error. Try to remove that in your aspx page

TARESH PRAJAPATI said...

can you give me idea that how to give privileges to staff member as per their work like distributormaintain, accountent, ordermaintain etc. plz sir give me a solution

Ajay said...

Hi I am Ajay.
I like you code but In my broser not displying the Images. Plz help me.

Ajay said...

In my Database I got the NULL value

sudeep said...

simple n good example.

Anonymous said...

I couldn't find out my connectionString, how can I set? and what is exactly the data source?

aarthi said...

sir
i get the following error when i run the above code...please helpBoth DataSource and DataSourceID are defined on 'gvImages'. Remove one definition.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Both DataSource and DataSourceID are defined on 'gvImages'. Remove one definition.

naresh said...

Hi buddy. I need one help,
I can create a directory and upload images dynamically in my local machine from asp.net C#.

When i host it and run from browser.It asks me server permission to create, which is understandable.

I need to store images to folder and retrieve it from database using image path. i dont want to store images in database to speed perfomance.

please help me ...

Anonymous said...

there is a difficult on finding the script..
the web structure is too mess

Abdus Samadh.K said...

Hi suresh, this post is superb.....keep on posting these kinda interesting posts

Anonymous said...

hai Suresh .i am facing a problem with inserting an image in a table and my database is sql server, how to insert an image into the db using simple query

kman said...

hai Suresh how ca i automatically resiese the image before upload into the gridview

kman said...

hai Suresh how can i automatically resieze the images when uploaadin into the grid view

Suresh Dasari said...

@kman...
Check below posts to resize image before upload without losing quality
http://www.aspdotnet-suresh.com/2011/05/how-to-resize-size-image-without-losing.html

Parvathaneni NagaVeerendra said...

sir the image is not saved in the root folder can you help me.

Anonymous said...

can someone change the code to asp.net

Anonymous said...

i want to display image and upload image in listview directly from database whose datatype is varbinary(max).pls help me i have searched it on the net but doesn't get the result.
i have used sqldatasource control.

Anonymous said...

Hi suresh

Anonymous said...

hello sir..
i've tried with ur previous solutions.
image path is storing in db table.and image is storing in images folder in project..but unable to display the image in grid.
Please help me out.

Anonymous said...

I m face a problem when i upload image at web server it shows Error

Access to the path 'C:\inetpub\vhosts\celebritybidding.com\httpdocs\Admin\laughing_kitten.jpg' is denied.

Please tell me other way to upload images or file to web server ...

Ravindra

Web Hosting said...

I am trying to upload the images to web server ,but it shows error

Access to the path 'C:\inetpub\vhosts\celebritybidding.com\httpdocs\Admin\laughing_kitten.jpg' is denied.

Please tell me another way if any

Suresh Dasari said...

@you3host...
Try to change the images path to D:\Images and try it will work for you..

Anonymous said...

Hi, can i use the same method to save the image file path into DB using asyncfileupload?

Junz Tan said...

Hi suresh, I have some problem.
After I upload the image, the gridview cannot display the image. Just a crossbar image. Please help.

tanisha said...

Thanks for sharing suresh

Aswini said...

hi sir
I tried this code but i got a null reference exception can u find out this

vanitha said...

Hi.. i have to save image into a folder and display it using image control. i have already done it but the problem is while displaying images from folder it must be based on the maximum pay..
can any one tell me how to perform this??

Aakash Doshi said...

exactly copied the same code..its working perfectly but it displays only image path and not image thumbnail..please let me know why??

bharath said...

could you please help me to delete the image from folder while deleting the row from gridview

Anonymous said...

sir this code is really very useful for me ..
but there is a some problem when i upload image t i am not able to show images in gridview what is the reason behind this?

Unknown said...

hi this is great....can please post a code for the same with ms access...because am a beginner..so please can u....?

Unknown said...

RUSESH SIR PLZ SEND ME A IMAGE GALLERY WEBSITE IN ASP.NET WITH VB CODE PLZ SIR PLZ PLZ.....

Unknown said...

cool haaan i m successfully retrieve img frm database....epieeeeeeeeeeeeeeeeeeee

surendra said...

good effort ............but after uploading image it is not showing image in the gridview...one question more...when we are uploading image....the path of image is saved in database or actual image.. please make me clear..

Anonymous said...

Can you tell me how to save files in folder at server side using silverlight via WCF enabled service

Unknown said...

successfully retrieve img frm database ok ,but i saved path only in databas .my task is how to save and retrive through byte format.

darpan pathak said...

sir thank you very much for the tutorial. But if i try to apply this stuff on my website, Its not working. Its shows an error like file or directory not found. please help me

Suresh Dasari said...

@darpan pathak....
i hope that problem because of you forgot to create folder in your application. please check the post clearly and do it. It will work for you....

darpan pathak said...

sir i have created folder and i am very sure about it. I think there must be some problem in this line fileuploadimages.SaveAs(Server.MapPath("Images/"+filename));

whenever i use this code with localhost it works well and save images in local folder name : Images

But on my server not working :(

darpan pathak said...

see this link

http://image.redmelonz.com/

i have uploaded this image through local host and created database on server all is set but if i am trying to upload image online its not working.

folder is also there to save uploaded images and i want to use the same script.

Suresh Dasari said...

@darpan pathak...
WHile you deploy code in server the path of the images folder will check it. you need to update the path of images folder according to your server folder path...

darpan pathak said...

sry ... can u please give me its example ??

i have tried

fileuploadimages.SaveAs(Server.MapPath("http://image.redmelonz.com/Images/"+filename));

fileuploadimages.SaveAs(Server.MapPath("87.98.142.251/Images/"+filename));

fileuploadimages.SaveAs(Server.MapPath("ftp://87.98.142.251/Images/"+filename));

darpan pathak said...

if you dont mind sir can i have your email ID ??

my email is
pathakdarpan77@gmail.com

it is very urgent for me to solve this issue ...

darpan pathak said...

sir i am waiting for your reply. help me sir

Unknown said...

hey my project name is Classified like quiker or olx etc nd i hav design it bt i have one problem abt database i am unable to make database design for the this so can anybody help me..

Unknown said...

you can give any related msg on shilpa2916@gmail.com pls sir help me..to get out of this problem...

Unknown said...

Hi Suresh,
I understood the above code but i want to store the image in specific folder by giving some id to that and Dynamically i want to generate new folder for storing another image.
I am using
FileUpload.saveas(sever.map(imgpath))
but with these method i am able to store the image in project folder and i want to create a new folder etither in project folder or anywhere in machine and in that folder again one new folder with some name and in that i want to save image with unique id.

Please
help me

Lavish Maheshwari

Unknown said...

Hi...Suresh..This is chandru...

Your link is very useful.... Thank you so much...

But suresh i don't nu anything about C# pls post pgms regarding C#...

Thanks in advance...

navya said...

Thanks for sharing.....

Anonymous said...

nvkjhbjb

ShireeshaKandukoori said...

Hi suresh..I did the samething as u explained here but in my gridview it is displaying the filepath instead of images please give me a solution.

Anonymous said...

YES OK GOOD BUT, YOU DIDNOT EXPLAIN ANYTHING ABOUT DATABASE, DID YOU DO IT WITH MSSQL OR WHAT? PLEASE BE OBVIOUS NEXT TIME, OR DID YOU USE MYSQL, WHAT IS THE NAME OF THE DATABASE , WHAT IS THE NAME OF THE DATA TABLE? YOU DIDNOT EXPLAIN ANYTHING? I DIDNT UNDERSTAND ANYTHING FROM YOUR CONNECTION STRING?

Anonymous said...

why cant i see the saved image in my images folder in my solution explorer..plz help

Wasif said...

Hey Suresh...

i got this error
"The name 'fileuploadimages' does not exist in the current context."

i have tried a lot but did not able to resolve it.

amir said...

hello sir i want to use acess as database for this program will u plz tell me how can i create database in access?
amirsalgar@yahoo.com

AMAR MANE DATABASE said...

suresh,

how to resize image automatcaly before display in gridviw or table..

Vikas Shukla said...

I am not able upload image in the Gridview.. instead it showing Path ..

ID ImageName ImagePath
1 2010_clash_of_the_titans_023.jpg Images/2010_clash_of_the_titans_023.jpg


where am i missing culd you plz help Me...



Thank You

Hanimi said...

i have uploaded this image through local host and created database on server all is set but if i am trying to upload image online its not working.

folder is also there to save uploaded images and i want to use the same script.

Anonymous said...

hi Suresh, I understand everything in the script but say if I have a user login control, what can I do to add the userid to the database after the user has logined using the login control?

C.D.Malavi said...

Hello suresh Dasari,

This code is working fine,the folder is created and the image name and image path are getting inserted at database , but the problem is when I Display in Grid view its showing the image Path instead of images.

The same as Vikas Shukla's problem

I couldn't find the solution.

Please help me to resolve this problem

Unknown said...

Hi,

I have one doubt on this if we upload multiple file with single name , what happen in this sitiutaion, please help me,

Thanks in advance,
Jayakumar

Ankur Jain said...

Hello Suresh,
I want to save the image in the folder & their path in database table with the help of "jquery or jquery plus webservice" , so that the page is not post back. Please provide me such a code.

Anonymous said...

hi suresh,
i have a problem the images save in folder but images not save in database.

pravindstranger said...

Hi Suresh,

in real time application is it correct to save file on server or in database before submitting complete form detail along with image of photo,
need help in scenario where i want to store image temporarily somewhere and once i submit complete transaction then only actual images gets saved in server physical path or in database.
help appreciated.... :)

joshila said...

sir can u pls tell how to delete images from gridview using checkbox...

AshisH PaL said...

sir, suppose same name image save in folder ( mine a.png already save in folder and again time user put the same name image like a.png, how to different between this two image ),
And user fetch the owner image display in grid view and other content,

place sir send me information and hint because i am put this model in my project....:)

Unknown said...

hi
i need code for inserting and retrieving image and its description from database using listview .. but image path should be stored in database and image stored in local folder like (~/images/)..

Thank You..

Plz reply as soon as...

Sagar ..
patilsagar224@gmail.com

Hasmukh Prajapati said...

hi suresh

Thanks for a nice example,
i have one major issue, that i want to Save image in folder but in different location not in application folder and store path in DB

like image folder is d:\Image\Image1.jpg
Application is in C:\Inetpub\wwwroot\DMS
Database is on same or other Machine.

all thing is done but i am not able to see Image in grid.
can you help me where is my mistake or what will be issue?

shashi shanker singh said...

it shows invalid ImpagePath object..

Anonymous said...

thanks for detailed explaination..
I have a doubt sir,
assume the sample code above is a category page (with name and image)
how can i create a subcategory page with a dropdownlist so that category name provided in previous page can populate in it and below that same subcategoryname and image can be added and displayed in gridview..

Anonymous said...

can u provide some help for the above problem... my mail id is
antonyvictor1989@gmail.com...

thanks in advance...

Saurabh Dubey said...

can you explain how to incorporate "adChoices" into my application just like you incorporated into your website?

Ecomatepack said...

C:\Inetpub\vhosts\mlcsdabwali.com\httpdocs\SlideImages\1.jpg' is denied please help me

Anonymous said...

Sir i need to know how to rename a folder that we create inside the web site please help me .

Unknown said...

sir how can i update an image similarly like other data with in gridview.structure of grid view like this
{ id username address photo }

Unknown said...

how to load images or text alternat from data base if type is not decide like fetch as post on facebook like page

Unknown said...

Hi... this is a very good tutorial indeed.
btw, can you please make the same article but in vb format.
I really need it.

Thank You so much..

Anonymous said...

Hey suresh,
I am antony. Is there any possibilities to have original image in sql instead of having only the path reference.

Unknown said...

hi suresh

I understood the above code but i want to store the image in specific folder by giving some id to that and Dynamically i want to generate new folder for storing another image.
I am using
FileUpload.saveas(sever.map(imgpath))
but with these method i am able to store the image in project folder and i want to create a new folder etither in project folder or anywhere in machine and in that folder again one new folder with some name and in that i want to save image with unique id.

Unknown said...

very nice work suresh ,,,,,,,,,

Unknown said...

hi Suresh, how to view images into image control?, using 'nvarchar' datatype for storing the image path.
I need to upload image and view image on the same page of ASP.net(c# )

BMe said...

it's really works bro thanks u are awesome :)

Vikas Mann said...

hii suresh...... m getting ID can't Be NULL error plzz tell me how to solve it

Unknown said...

can u explain upload image and editing in gridview..

Unknown said...

hi suresh, am trying to save the image in a folder( which is located in my c drive) and the c drive path will be stored in database can u plz help me to solving this issue....

Test said...

Thanks Dear.

shahab_iglesias said...

Hello Suresh...How can i stop saving image into Project Folder if other datas are not saved into database in C#

Unknown said...
This comment has been removed by the author.
Unknown said...

hi..
i want to upload default image through my application'folder or u can say virtual path when i dont select any image through fileupload control in asp.net. please help me out.

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.