0

i am building a social network site using asp.net c# , And i am having a problem with image uploading, when i upload an image to the database it name will be changed and it save on real path i mentioned. but i cannot get it to the database table.

This is code

<asp:FileUpload ID="ProfilePic" runat="server" style="margin-top: -10px" />
<asp:Button ID="Register" runat="server" Text=" Register" 
                        onclick="Button2_Click" ValidationGroup="RegisterGroup" Font-Size="Larger" Height="30px" style="text-align: left; margin-left: 106px" Width="103px" />

This is code behind file

    if (ProfilePic.HasFile)
    {
        if ((ProfilePic.PostedFile.ContentType == "image/jpeg") ||
           (ProfilePic.PostedFile.ContentType == "image/png") ||
           (ProfilePic.PostedFile.ContentType == "image/bmp") ||
           (ProfilePic.PostedFile.ContentType == "image/gif"))
        {

            if (Convert.ToInt64(ProfilePic.PostedFile.ContentLength) < 10000000)
            {
                string photofolder = Path.Combine(@"C:\Users\Supun\Documents\Visual Studio 2013\WebSites\MeetYou\ProfilePic", User.Identity.Name);

                if (!Directory.Exists(photofolder))
                    Directory.CreateDirectory(photofolder);


                string extension = Path.GetExtension(ProfilePic.FileName);
                string uniqueFileName = Path.ChangeExtension(ProfilePic.FileName, DateTime.Now.Ticks.ToString());

                ProfilePic.SaveAs(Path.Combine(photofolder, uniqueFileName + extension));







    // string harshpassword = FormsAuthentication.HashPasswordForStoringInConfigFile(RegPassword.Text, "shar1");

    if (IsPostBack)
    {

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
        conn.Open();
        string checkemail = "select count(*) from UserData where Email='" + RegEmail.Text + "'";
        SqlCommand com = new SqlCommand(checkemail, conn);
        int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
        if (temp == 1)
        {


            string message = "Email already Exits";
            ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('" + message + "');", true);


        }

        else{

             try{
             //   SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
                Guid newGuid = Guid.NewGuid();

                string inserQuery = "insert into UserData(YourName,Email,Password,Gender,Birthday,AboutMe,Country,ID) values (@YName,@REmail,@RPassword,@DDownGender,@MTextBox,@RAboutMe,@DCountry,@ID)";
                SqlCommand comm = new SqlCommand(inserQuery, conn);
                comm.Parameters.AddWithValue("@YName", Your_Name.Text);
                comm.Parameters.AddWithValue("@REmail", RegEmail.Text);
                comm.Parameters.AddWithValue("@RPassword", RegPassword.Text);
                comm.Parameters.AddWithValue("@DDownGender", DropDownGender.SelectedItem.ToString());
                comm.Parameters.AddWithValue("@MTextBox", Birthday.Text);
                comm.Parameters.AddWithValue("@RAboutMe", RegAboutMe.Text);
                comm.Parameters.AddWithValue("@DCountry", DropDownCountry.SelectedItem.ToString());
                comm.Parameters.AddWithValue("@ID", newGuid.ToString());
                comm.Parameters.AddWithValue("@ProfilePic", uniqueFileName);


                comm.ExecuteNonQuery();

                Session["RegEmail"] = RegEmail.Text; 
                Response.Redirect("SecurityQuestion.aspx");

              //  string message = "Registration Complete!!! Please login in";
               // ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('" + message + "');", true);



            }



    catch (Exception ex)    {

        Response.Write("Error -->" + ex.ToString());


                            }
        }
        conn.Close();




}

And this is sql code

CREATE TABLE [dbo].[UserData] (
[YourName]    VARCHAR (50)  NULL,
[Email]       VARCHAR (50)  NOT NULL,
[Password]    VARCHAR (50)  NULL,
[Gender]      VARCHAR (50)  NULL,
[Birthday]    VARCHAR (50)  NULL,
[AboutMe]     VARCHAR (50)  NULL,
[Country]     VARCHAR (50)  NULL,
[ID]          NVARCHAR (50) NOT NULL,
[ProfilePic ] IMAGE         NULL,
CONSTRAINT [PK_UserData] PRIMARY KEY CLUSTERED ([Email] ASC)

);

Could someboday tell me how to get this name changing image to the database table, And tell me guys what is the good method to save images on database table,

now i use this to save image

[ProfilePic ] IMAGE         NULL,

1 Answers1

0

I can see two errors above.

First: you don't add the ProfilePIC field in the INSERT text, so adding the parameter does nothing.

Second: The ProfilePIC field is an Image field, but if you want to store a path to your image it should be a normal NVARCHAR

So, if you want to store just the full filename of the saved image, you need to change that column type using Sql Server Management Studio and then change the query text to

 string inserQuery = @"insert into UserData(YourName,Email,Password,Gender,
                                            Birthday,AboutMe,Country,ID, ProfilePic) 
                       values (@YName,@REmail,@RPassword,@DDownGender,
                               @MTextBox,@RAboutMe,@DCountry,@ID, @ProfilePic)";

However I suggest to avoid a fixed path for your images. You should really read the location of your profile pictures from some kind of external configuration file or even a database table with global option for your program. So you don't need to change your code in case you want to move the folder where the pictures are stored

Steve
  • 213,761
  • 22
  • 232
  • 286
  • oh i forgot to add it to the insert field, sorry for that, i fixed it. but i cannot convert image into nvarchar, it gives me error The type for column ProfilePic in table [dbo].[UserData] is currently IMAGE NULL but is being changed to NVARCHAR (50) NULL. There is no implicit or explicit conversion. – Softwares Aŋɖ Tricks Dec 28 '14 at 13:36
  • Not sure from where this error is coming, but you could drop the column and rebuild it with the nvarchar(255) type – Steve Dec 28 '14 at 13:40
  • yes i did as u said. could you tell me what other errors are from this codes, is this codes right ??? comm.Parameters.AddWithValue("@ProfilePic", uniqueFileName); – Softwares Aŋɖ Tricks Dec 28 '14 at 13:45
  • If you have changed that field to be NVARCHAR the code should work unless there is something wrong with the datatypes of your columns and the datatypes of the parameters assumed by AddWithValue. You really should read these two articles on that: [Can we stop using AddWithValue() already?](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) and also [How Data Access Code Affects Database Performance](http://msdn.microsoft.com/en-us/magazine/ee236412.aspx) – Steve Dec 28 '14 at 13:50
  • Another thing that should be improved is the storing of passwords in clear text. This is a great security _No-No_ You never store passwords in clear text inside a database field. Anyone that could gain access to this database could create big problems with your site and users. Study how to store an HASH of your passwords. A [starting point here](http://stackoverflow.com/questions/1054022/best-way-to-store-password-in-database) – Steve Dec 28 '14 at 13:54
  • Thanks for your ideas, i edited this code as u said, but it gives me an error like this System.Data.SqlClient.SqlException (0x80131904): String or binary data would be truncated. The statement has been terminated. – Softwares Aŋɖ Tricks Dec 28 '14 at 13:59
  • Check all of your field's size is enough to store the inputs. – Steve Dec 28 '14 at 14:17