如果以编程方式向ImageUrl
添加ImageControl
,我需要帮助。我得到了这段代码,但我不能(我不知道如何)添加存储在数据库中的路径。
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath(".") + "//images//" + str);
string path = "~//images//" + str.ToString();
con.Open();
SqlCommand cmd = new SqlCommand("insert into upload values('" + TextBox1.Text + "','" + path + "')", con);
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "Image uploaded";
SqlDataAdapter da = new SqlDataAdapter("Select img from upload", con);
DataTable dt = new DataTable();
da.Fill(dt);
Image1.ImageUrl =
}
else
{
Label1.Text = "Please select image";
}
}
答案 0 :(得分:0)
对于该特定场景,您已经拥有图像文件名和路径。您所需要的只是Image1.ImageUrl = ResolveUrl("~/images/" + fileName);
。
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = FileUpload1.FileName;
string path = string.Format("{0}\\images\\{1}",
HttpRuntime.AppDomainAppPath, fileName);
FileUpload1.PostedFile.SaveAs(path);
/* Save image information to database */
Image1.ImageUrl = ResolveUrl("~/images/" + fileName);
}
else
{
Label1.Text = "Please select image";
}
}
仅供参考: 您的代码容易受到SQL注入攻击。确保使用参数化查询。