用c#实现图片的上传和绑定

前台:

<td style="width: 94px; text-align: center; height: 23px;">
<asp:Label ID="labPhone" runat="server" Text="头像" Font-Size="9pt" Width="37px"></asp:Label></td>
<td style="width: 169px; text-align: center; height: 23px;">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" CausesValidation="False" OnClick="Button1_Click"
Text="上传" /></td>
<td style="width: 149px; height: 23px;">
</td>
</tr>
<tr>
<td style="text-align: center" colspan="2" rowspan="2">
</td>
<td style="width: 169px; text-align: left;">
<asp:Image ID="imgPhoto" runat="server" Height="120px" Width="90px" /></td>

还需要建立一个upFile文夹存储图片


后台:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon;
string strCon = "Data Source=.;Initial Catalog=db_04;Integrated Security=true";
protected void Page_Load(object sender, EventArgs e)
{
sqlcon = new SqlConnection(strCon);
sqlcon.Open();
string sqlstr = "select * from tb_Image order by date desc";
SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
DataSet myds = new DataSet();
myda.Fill(myds, "tb_Image");
DataRowView mydrv = myds.Tables["tb_Image"].DefaultView[0];



imgPhoto.ImageUrl = Convert.ToString(mydrv["Image"]);

// Response.Write("<script>alert('怎么样')</script>");

sqlcon.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
string filePath = "", fileExtName = "", mFileName, mPath;
if ("" != FileUpload1.PostedFile.FileName)
{
filePath = FileUpload1.PostedFile.FileName;
fileExtName = filePath.Substring(filePath.LastIndexOf(".")+1);
try
{
mPath = Server.MapPath("upFile/");
mFileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
FileUpload1.PostedFile.SaveAs(mPath + mFileName);
string sqlstr = "insert into tb_Image(Image) values('upFile\\"+ mFileName + "')";

sqlcon = new SqlConnection(strCon);
sqlcon.Open();
SqlCommand com = new SqlCommand(sqlstr,sqlcon);
com.ExecuteNonQuery();
sqlcon.Close();
Page_Load(sender,e);
}
catch (Exception error)
{
Response.Write("<script>alert('" + error.ToString() + "')</script>");
}
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xinying888888

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值