Reputation: 587
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();
}
}
}
Upvotes: 4
Views: 23918
Reputation:
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
Upvotes: 4