C# 通过文件上载和保存到数据库asp.net,可多次上载图像
好的,我正在尝试选择多个图像并将它们保存在asp.net中的数据库中。 我不想使用任何插件或任何类型的脚本 这是设计器页面:C# 通过文件上载和保存到数据库asp.net,可多次上载图像,c#,asp.net,file-upload,C#,Asp.net,File Upload,好的,我正在尝试选择多个图像并将它们保存在asp.net中的数据库中。 我不想使用任何插件或任何类型的脚本 这是设计器页面: <asp:FileUpload AllowMultiple="true" ID="fileuploadimages" runat="server" /> <asp:Button runat="server" ID="btnUpload" CssClass="btnStyle" Text="Upload Image" OnClick="btnUploa
<asp:FileUpload AllowMultiple="true" ID="fileuploadimages" runat="server" />
<asp:Button runat="server" ID="btnUpload" CssClass="btnStyle" Text="Upload Image"
OnClick="btnUpload_Click" />
到目前为止,我已经在button upload事件中完成了这项工作。它的作用是允许我选择多个文件,比如如果我选择3个图像,它会将第一个文件在我的数据库中保存三次,并将其保存在文件夹“Pictures”中一次,而不是全部保存三个
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();
}
}
}
protectedvoidbtnupload\u单击(对象发送方,事件参数e)
{
if(fileuploadimages.HasFile==false)
{
ScriptManager.RegisterStartupScript(Page,Page.GetType(),“key”,“警报('未上载文件')”,false);
}
其他的
{
foreach(fileuploadimages.PostedFiles中的var文件)
{
string filename=Path.GetFileName(fileuploadimages.PostedFile.filename);
fileuploadimages.SaveAs(Server.MapPath(“../Pictures/”+filename));
SqlCommand cmd=新的SqlCommand(“插入到
EventPageView(事件名称、事件文本、图像路径)
值(@EventName、@EventText、@ImagePath)”,conn);
cmd.Parameters.AddWithValue(“@ImagePath”,文件名);
cmd.Parameters.AddWithValue(“@EventName”,txtEventName.Text);
cmd.Parameters.AddWithValue(“@EventText”,txtEnterDesc.Text);
conn.Open();
cmd.ExecuteNonQuery();
康涅狄格州关闭();
BindDataList();
}
}
}
更改这两行:
string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);
fileuploadimages.SaveAs(Server.MapPath("../Pictures/" + filename));
到
我希望这会有帮助。因为您必须使用对象
文件
,所以只需删除一些额外的代码即可。
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("../Pictures/" + filename));