4

Okay, so I'm trying to select multiple images and save them in a database in asp.net. I don't want to use any plugins or any kind of scripts.

This is the designer page:

<asp:FileUpload AllowMultiple="true"  ID="fileuploadimages" runat="server" />
<asp:Button runat="server" ID="btnUpload" CssClass="btnStyle" Text="Upload Image"
 OnClick="btnUpload_Click" />

I have done this so far on the button upload event. What it does is that it allows me to select more than one file, like if I select 3 images, it saves the first file thrice in my database and saves it once in the folder "Pictures" instead of saving all three.

protected void btnUpload_Click(object sender, EventArgs e)
{
    if (fileuploadimages.HasFile == false)
    {
        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", "<script>alert('No File Uploaded.')</script>", false);
    }
    else    
    {
        foreach (var file in fileuploadimages.PostedFiles)
        {
            string filename =Path.GetFileName(fileuploadimages.PostedFile.FileName);

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

            SqlCommand cmd = new SqlCommand("Insert into
            EventPageView(Event_name,Event_Text,Image_Path)
            values(@EventName,@EventText,@ImagePath)", conn);

            cmd.Parameters.AddWithValue("@ImagePath", filename);
            cmd.Parameters.AddWithValue("@EventName", txtEventName.Text);
            cmd.Parameters.AddWithValue("@EventText", txtEnterDesc.Text);
            conn.Open();
            cmd.ExecuteNonQuery();

            conn.Close();
            BindDataList();
        }    
    }
}
1
  • 1
    just remove some extra codes. Commented Mar 30, 2016 at 2:03

1 Answer 1

4

Change those two lines line:

string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);

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

to

string filename = Path.GetFileName(file.FileName);

file.SaveAs(Server.MapPath("../Pictures/" + filename));

I hope it will help. Because you must use the object file

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.