Click here to Skip to main content
16,015,258 members
Articles / Web Development / ASP.NET
Tip/Trick

how to upload a JPG image and save it on SQL Server or servers hard Drive

Rate me:
Please Sign up or sign in to vote.
3.00/5 (2 votes)
29 Jan 2010CPOL1 min read 17.8K   8   2
In this article you will learn how to upload a JPG image and save it on SQL Server or servers hard Drive.To get started create a blank asp.net page, and add a File Upload Control from Standard tab of visual studio toolbar or add the following code to the section you have planned to add the...
In this article you will learn how to upload a JPG image and save it on SQL Server or servers hard Drive.
To get started create a blank asp.net page, and add a File Upload Control from Standard tab of visual studio toolbar or add the following code to the section you have planned to add the upload control.
    <br />
<asp:fileupload id="PicUpload" runat="server" /><br />

This adds a file browser control to your webpage, which you can select one file at a time from your local hard drive. Switch to code view and add the following code on top of your page, where other name spaces are imported.
<br />
Using Sytem.IO;<br />

switch back to design view, add button or image button to your page (name it Upload for example) and add the following code the buttons Click Event:
if (PicUpload.PostedFile != null)
        {
         HttpPostedFile Pic = PicUpload.PostedFile;
            if (Pic.ContentLength == 0)
            {
                Response.Write("فایل شما هیچ محتوایی ندارد!");
                return;
            }
        if (Path.GetExtension(Pic.FileName).ToLower() != ".jpg")
            {
                Response.Write("پسوند این فایل نامعتبر است.");
                return;
            }
        byte[] data = new Byte[Pic.ContentLength];
        Pic.InputStream.Read(data, 0, Pic.ContentLength);
        string SavePath = @"images/";
        newPic = new FileStream(Server.MapPath(SavePath + Pic.FileName), FileMode.Create);
        newPic.Write(data, 0, Pic.ContentLength);
        newPic.Close();
        }else
        {
            Response.Write("Please Select a File! ");
        }

In first line of the code we check if user has selected a file or not, if not the code will return an error message. Then we create a HttpPostedFile variable, called Pic, then we we verify the file length and extension( in this case we allow users to upload .JPG files only) This Lines read selected file in to a stream and makes it ready for saving :
<br />
byte[] data = new Byte[Pic.ContentLength];<br />
Pic.InputStream.Read(data, 0, Pic.ContentLength);<br />

now that we have the file in a stream we can save it by following code :
<br />
FileStream newPic = new FileStream(Server.MapPath(SavePath + Pic.FileName), FileMode.Create);<br />
newPic.Write(data, 0, Pic.ContentLength);<br />

You can use code bellow instead of above two lines to save your image in a SQL Server data base :
object objImage = data;
SqlConnection connection = new SqlConnection(connectionString);
string sql_insert = "INSERT INTO tblImage (picture) values (@img)";
SqlCommand command = new SqlCommand(sql_insert, connection);
SqlParameter parameter = new SqlParameter("@img", SqlDbType.Image);
parameter.Value = objImage;
command.Parameters.Add(parameter);
connection.Open();
command.ExecuteNonQuery();
connection.Close();

All you have to do is change your connection string and rename your database table name and column in sql_insert variable.

License

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


Written By
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralResponse.Write("???? ??? ??? ??????? ?????!"); this not reda... Pin
BhumitAhir19-Jan-12 6:35
BhumitAhir19-Jan-12 6:35 
GeneralReason for my vote of 5 it's very useful for me. Pin
BhumitAhir19-Jan-12 6:33
BhumitAhir19-Jan-12 6:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.