如何使用ajaxfileupload上传多个文件并将其插入数据库
本文关键字:插入 数据库 文件 ajaxfileupload 何使用 | 更新日期: 2023-09-27 18:20:57
我正在使用AjaxFileUpload控件上传多个图像文件。我正在做的是将文件保存到文件夹中,然后将其插入数据库。但我收到了一个上传错误。该文件既不会上传到文件夹中,也不会保存到表中。
这是我的aspx代码:
<div id="sliderinsert" style="position:absolute; padding-bottom:5px; background-color:gray; top: 24px; left: 13px;
width: 695px; height: 300px; margin-bottom: 1px; overflow:visible">
<ajaxToolkit:AjaxFileUpload style="position:absolute; width:695px; overflow:auto;max-height:600px" MaximumNumberOfFiles="7" AllowedFileTypes="jpg,jpeg,png,gif"
id="ajaxUpload1" OnUploadComplete="ajaxUpload1_UploadComplete" runat="server" Width="633px"/>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</div>
下面是我的代码:
protected void ajaxUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
id+=1;
string filename = Path.GetFileName(e.FileName);
string filepath = Server.MapPath("~/Images/Gallery/" + filename);
ajaxUpload1.SaveAs(filepath);
string Insert = "Insert into slider (slid,slurl) values (@id,@IMAGE_PATH)";
SqlCommand cmd = new SqlCommand(Insert, con);
cmd.Parameters.AddWithValue("@IMAGE_PATH", filepath);
cmd.Parameters.AddWithValue("id", id);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
cmd.Dispose();
}
}
在PageLoad事件中,我得到了表的max(id),并在Upload complete事件中递增它,然后将文件插入表中。
谁能告诉我我在这里犯了什么错误吗。请帮我摆脱困境。。。
检查以下给定代码:
protected void AjaxFileUpload1_UploadComplete1(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)<br>
{
string filepath = (Server.MapPath("~/Images/") +Guid.NewGuid()+ System.IO.Path.GetFileName(e.FileName));<br>
AjaxFileUpload1.SaveAs(filepath);<br>
string fl = filepath.Substring(filepath.LastIndexOf("''"));<br>
string[] split = fl.Split('''');<br>
string newpath = split[1];<br>
string imagepath = "~/Images/" + newpath;<br>
string Insert = "Insert into IMAGE_PATH (IMAGE_PATH) values (@IMAGE_PATH)";<br>
SqlCommand cmd = new SqlCommand(Insert, con);<br>
cmd.Parameters.AddWithValue("@IMAGE_PATH", newpath);<br>
con.Open();<br>
cmd.ExecuteNonQuery();<br>
con.Close();<br>
cmd.Dispose();<br>
}
如果您第一次将图像保存在应用程序文件夹中,请确保~/Images/Gallery/path是否存在。
您可以直接将值插入滑块表中,而不使用参数。尝试低于代码
protected void ajaxUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
id += 1;
string filename = Path.GetFileName(e.FileName);
string filepath = Server.MapPath("~/Images/Gallery/" + filename);
ajaxUpload1.SaveAs(filepath);
string Insert = "Insert into slider (slid,slurl) values (" + @id + ",'" + @IMAGE_PATH + "')";
SqlCommand cmd = new SqlCommand(Insert, con);
cmd.CommandType = CommandType.Text;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
cmd.Dispose();
}
}