连接未关闭。连接的当前状态是打开的。 (多张图片上传)
The connection was not closed. The connection's current state is open. (Multiple Image Upload)
上传多张图片时出现错误 Maximum request length exceeded
但是当我增加 Web.Config
文件的大小时现在出现错误 The connection was not closed. The connection's current state is open.
不知道为什么。
请检查代码并让我知道我错在哪里
protected void btnAdd_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == false)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", "<script>alert('Please select the file.')</script>", false);
}
else
{
foreach (var file in FileUpload1.PostedFiles)
{
string filename = Path.GetFileName(file.FileName);
FileUpload1.SaveAs(Server.MapPath("/GalleryImages/" + filename));
SqlCommand cmd = new SqlCommand("Insert into tbl_gallery_stack(gallery_id, image_title, image_description, image_path) values (@gallery_id,@image_title,@image_description,@image_path)", conn);
cmd.Parameters.AddWithValue("@gallery_id", ddlImagesId.SelectedValue);
cmd.Parameters.AddWithValue("@image_title", txtImageTitle.Text);
cmd.Parameters.AddWithValue("@image_description", txtImageDescription.Text);
cmd.Parameters.AddWithValue("@image_path", filename);
conn.Open();
cmd.ExecuteNonQuery();
BindGrid();
}
}
}
我的web.config文件代码:-
<system.web>
<httpRuntime maxRequestLength="1073741824" />
</system.web>
最近发生的事情
当我上传多张图片时,无法在网格视图中查看。而且在 table 中插入了多个条目..
查看代码:-
<asp:GridView ID="grdGalleryData"
runat="server"
Width="100%" border="1"
Style="border: 1px solid #E5E5E5;"
CellPadding="3"
AutoGenerateColumns="False"
AllowPaging="True"
PageSize="3"
OnPageIndexChanging="grdGalleryData_PageIndexChanging"
CssClass="hoverTable"
DataKeyNames="Id"
>
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:CheckBox ID="chkDelete" runat="server" />
</ItemTemplate>
<HeaderStyle CssClass="k-grid td"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="gallery_id" HeaderText="Id" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="image_title" HeaderText="Gallery title" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="image_description" HeaderText="Gallery Description" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Images" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:Image ID="imgDisplay" runat="server" ImageUrl='<%#Getimage(Eval("image_path").ToString()) %>' Width="100px" Height="100px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
另见后面的代码:-
protected void btnAdd_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == false)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", "<script>alert('Please select the file.')</script>", false);
}
else
{
foreach (var file in FileUpload1.PostedFiles)
{
string filename = Path.GetFileName(file.FileName);
FileUpload1.SaveAs(Server.MapPath("/GalleryImages/" + filename));
SqlCommand cmd = new SqlCommand("Insert into tbl_gallery_stack(gallery_id, image_title, image_description, image_path) values (@gallery_id,@image_title,@image_description,@image_path)", conn);
cmd.Parameters.AddWithValue("@gallery_id", ddlImagesId.SelectedValue);
cmd.Parameters.AddWithValue("@image_title", txtImageTitle.Text);
cmd.Parameters.AddWithValue("@image_description", txtImageDescription.Text);
cmd.Parameters.AddWithValue("@image_path", filename);
conn.Open();
cmd.ExecuteNonQuery();
BindGrid();
conn.Close();
}
}
}
protected string Getimage(string img)
{
if (img != "")
return ("~/GalleryImages/" + img);
else
return ("Images/noimg.gif");
}
BindGrid
方法
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropdownlist();
BindGrid();
}
}
private void BindGrid()
{
string conString = ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString;
SqlCommand cmd = new SqlCommand("Select Id, gallery_id, image_title, image_description, image_path from tbl_gallery_stack order by Id desc");
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
grdGalleryData.DataSource = dt;
grdGalleryData.DataBind();
}
}
}
}
执行查询后关闭连接。
conn.Open();
cmd.ExecuteNonQuery();
//Close connection
conn.Close();
您收到异常是因为您从未关闭连接。 SqlConnection
通常一次只能执行一个命令。只需添加:
conn.Close();
由于您要遍历一组文件然后将数据插入数据库,请在 using 块中实例化连接(以便正确处理),如果您想查看所有上传的图像一次在 Grid 中,那么我建议您将 BindGrid() 函数移出 ForEach 循环。
下面是一些示例代码:
foreach (var file in FileUpload1.PostedFiles)
{
try
{
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("/GalleryImages/" + filename)); //Save each file to disk.
//Also please evaluate you requirement and if you are supposed to loop over relatively
// large collection then you can opt for some batch insert/update of records at-a-go
// instead of calling database multiple times, if your database offer support.
using(var conn = new SqlConnection("YOUR CONNECTION STRING VALUE HERE"))
using(var cmd = new SqlCommand("Insert into tbl_gallery_stack(gallery_id,image_title, image_description, image_path) values (@gallery_id,@image_title,@image_description,@image_path)", conn))
{
cmd.Parameters.AddWithValue("@gallery_id", ddlImagesId.SelectedValue);
cmd.Parameters.AddWithValue("@image_title", txtImageTitle.Text);
cmd.Parameters.AddWithValue("@image_description", txtImageDescription.Text);
cmd.Parameters.AddWithValue("@image_path", filename);
conn.Open();
cmd.ExecuteNonQuery();
}
}
catch(Exception ex) //I suggest you handle all those db/network specific exceptions first
{
//Log the exception details here and either continue over the loop or return based on application requirement.
}
}
BindGrid(); //Assuming you are getting data from database inside this method and binding to Grid.
另外,为了确保数据完整性,最好将磁盘文件存储逻辑移动到循环末尾,或许将整个数据库和文件逻辑设置在 try catch 块中。因此,如果数据库中发生某些错误,您的磁盘文件也不会被创建为未映射。
希望本文能对您的问题有所帮助。
上传多张图片时出现错误 Maximum request length exceeded
但是当我增加 Web.Config
文件的大小时现在出现错误 The connection was not closed. The connection's current state is open.
不知道为什么。
请检查代码并让我知道我错在哪里
protected void btnAdd_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == false)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", "<script>alert('Please select the file.')</script>", false);
}
else
{
foreach (var file in FileUpload1.PostedFiles)
{
string filename = Path.GetFileName(file.FileName);
FileUpload1.SaveAs(Server.MapPath("/GalleryImages/" + filename));
SqlCommand cmd = new SqlCommand("Insert into tbl_gallery_stack(gallery_id, image_title, image_description, image_path) values (@gallery_id,@image_title,@image_description,@image_path)", conn);
cmd.Parameters.AddWithValue("@gallery_id", ddlImagesId.SelectedValue);
cmd.Parameters.AddWithValue("@image_title", txtImageTitle.Text);
cmd.Parameters.AddWithValue("@image_description", txtImageDescription.Text);
cmd.Parameters.AddWithValue("@image_path", filename);
conn.Open();
cmd.ExecuteNonQuery();
BindGrid();
}
}
}
我的web.config文件代码:-
<system.web>
<httpRuntime maxRequestLength="1073741824" />
</system.web>
最近发生的事情
当我上传多张图片时,无法在网格视图中查看。而且在 table 中插入了多个条目..
查看代码:-
<asp:GridView ID="grdGalleryData"
runat="server"
Width="100%" border="1"
Style="border: 1px solid #E5E5E5;"
CellPadding="3"
AutoGenerateColumns="False"
AllowPaging="True"
PageSize="3"
OnPageIndexChanging="grdGalleryData_PageIndexChanging"
CssClass="hoverTable"
DataKeyNames="Id"
>
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:CheckBox ID="chkDelete" runat="server" />
</ItemTemplate>
<HeaderStyle CssClass="k-grid td"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="gallery_id" HeaderText="Id" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="image_title" HeaderText="Gallery title" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="image_description" HeaderText="Gallery Description" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Images" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:Image ID="imgDisplay" runat="server" ImageUrl='<%#Getimage(Eval("image_path").ToString()) %>' Width="100px" Height="100px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
另见后面的代码:-
protected void btnAdd_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == false)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", "<script>alert('Please select the file.')</script>", false);
}
else
{
foreach (var file in FileUpload1.PostedFiles)
{
string filename = Path.GetFileName(file.FileName);
FileUpload1.SaveAs(Server.MapPath("/GalleryImages/" + filename));
SqlCommand cmd = new SqlCommand("Insert into tbl_gallery_stack(gallery_id, image_title, image_description, image_path) values (@gallery_id,@image_title,@image_description,@image_path)", conn);
cmd.Parameters.AddWithValue("@gallery_id", ddlImagesId.SelectedValue);
cmd.Parameters.AddWithValue("@image_title", txtImageTitle.Text);
cmd.Parameters.AddWithValue("@image_description", txtImageDescription.Text);
cmd.Parameters.AddWithValue("@image_path", filename);
conn.Open();
cmd.ExecuteNonQuery();
BindGrid();
conn.Close();
}
}
}
protected string Getimage(string img)
{
if (img != "")
return ("~/GalleryImages/" + img);
else
return ("Images/noimg.gif");
}
BindGrid
方法
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropdownlist();
BindGrid();
}
}
private void BindGrid()
{
string conString = ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString;
SqlCommand cmd = new SqlCommand("Select Id, gallery_id, image_title, image_description, image_path from tbl_gallery_stack order by Id desc");
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
grdGalleryData.DataSource = dt;
grdGalleryData.DataBind();
}
}
}
}
执行查询后关闭连接。
conn.Open();
cmd.ExecuteNonQuery();
//Close connection
conn.Close();
您收到异常是因为您从未关闭连接。 SqlConnection
通常一次只能执行一个命令。只需添加:
conn.Close();
由于您要遍历一组文件然后将数据插入数据库,请在 using 块中实例化连接(以便正确处理),如果您想查看所有上传的图像一次在 Grid 中,那么我建议您将 BindGrid() 函数移出 ForEach 循环。
下面是一些示例代码:
foreach (var file in FileUpload1.PostedFiles)
{
try
{
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("/GalleryImages/" + filename)); //Save each file to disk.
//Also please evaluate you requirement and if you are supposed to loop over relatively
// large collection then you can opt for some batch insert/update of records at-a-go
// instead of calling database multiple times, if your database offer support.
using(var conn = new SqlConnection("YOUR CONNECTION STRING VALUE HERE"))
using(var cmd = new SqlCommand("Insert into tbl_gallery_stack(gallery_id,image_title, image_description, image_path) values (@gallery_id,@image_title,@image_description,@image_path)", conn))
{
cmd.Parameters.AddWithValue("@gallery_id", ddlImagesId.SelectedValue);
cmd.Parameters.AddWithValue("@image_title", txtImageTitle.Text);
cmd.Parameters.AddWithValue("@image_description", txtImageDescription.Text);
cmd.Parameters.AddWithValue("@image_path", filename);
conn.Open();
cmd.ExecuteNonQuery();
}
}
catch(Exception ex) //I suggest you handle all those db/network specific exceptions first
{
//Log the exception details here and either continue over the loop or return based on application requirement.
}
}
BindGrid(); //Assuming you are getting data from database inside this method and binding to Grid.
另外,为了确保数据完整性,最好将磁盘文件存储逻辑移动到循环末尾,或许将整个数据库和文件逻辑设置在 try catch 块中。因此,如果数据库中发生某些错误,您的磁盘文件也不会被创建为未映射。
希望本文能对您的问题有所帮助。