ASP.NET如何把图片上传到数据库!sqlserver
2个回答
展开全部
前台:<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:Button ID="Button1" runat="server" Text="确 定" OnClick="Button1_Click" />
.cs:
public string imgurl = "";
//编辑数据
protected void Button1_Click(object sender, EventArgs e)
{
try
{
if (FileUpload1.FileName != "")
{
string filename = Path.GetFileName(FileUpload1.FileName); //获取图片名称
string ext = filename.Substring(filename.LastIndexOf(".") + 1); //获取图片扩展名
string time = DateTime.Now.ToString("yyyy-MM-dd_HHmmss_ffff"); //获取当前时间
if (ext == "jpg" || ext == "gif" || ext == "png" || ext == "bmp" || ext == "jpeg")
{
string path = time + '.' + ext;
string create = string.Concat("uploads");//文件夹名称
string createpath = HostingEnvironment.MapPath("~/" + create);
FileUpload1.SaveAs(Path.Combine(createpath, Path.GetFileName(path))); //存储图片
imgurl = string.Concat(create, "/", path); //数据库路径
}
else
{
Response.Write("<script language='javascript'>alert('图片格式不正确')</script>");
return;
}
}
else
{
imgurl = Label1.Text;
}
int i = DBHelper.ExecuteSql("insert into IMG (imgurl)values('" + imgurl + "')");
if (i == 1)
{
Function.Message(this, "上传成功!");
}
else
{
Function.Message(this, "上传失败!");
}
}
catch
{
Function.Message(this, "内容中含有非法字符,请重试~");
}
}
希望对你有用,,祝你成功!
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:Button ID="Button1" runat="server" Text="确 定" OnClick="Button1_Click" />
.cs:
public string imgurl = "";
//编辑数据
protected void Button1_Click(object sender, EventArgs e)
{
try
{
if (FileUpload1.FileName != "")
{
string filename = Path.GetFileName(FileUpload1.FileName); //获取图片名称
string ext = filename.Substring(filename.LastIndexOf(".") + 1); //获取图片扩展名
string time = DateTime.Now.ToString("yyyy-MM-dd_HHmmss_ffff"); //获取当前时间
if (ext == "jpg" || ext == "gif" || ext == "png" || ext == "bmp" || ext == "jpeg")
{
string path = time + '.' + ext;
string create = string.Concat("uploads");//文件夹名称
string createpath = HostingEnvironment.MapPath("~/" + create);
FileUpload1.SaveAs(Path.Combine(createpath, Path.GetFileName(path))); //存储图片
imgurl = string.Concat(create, "/", path); //数据库路径
}
else
{
Response.Write("<script language='javascript'>alert('图片格式不正确')</script>");
return;
}
}
else
{
imgurl = Label1.Text;
}
int i = DBHelper.ExecuteSql("insert into IMG (imgurl)values('" + imgurl + "')");
if (i == 1)
{
Function.Message(this, "上传成功!");
}
else
{
Function.Message(this, "上传失败!");
}
}
catch
{
Function.Message(this, "内容中含有非法字符,请重试~");
}
}
希望对你有用,,祝你成功!
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询