图片上传
求把图片通过fileupload上传到站点目录,并通过gridview显示出来,求大仙指导啊!求具体代码
--------------------编程问答--------------------
我的意思是往数据库里存图片的完整路径,并通过gridview显示出来。比如说网站发布后,网友随意上传图片,在网站后台都能通过gridview显示
--------------------编程问答--------------------
这里是显示文件
if (dt.ImageURL != "")
{
aimgshow.Src = "~/" + dt.ImageURL;
}
这里是保存文件代码:
if (FileUpload1.HasFile)
{
try
{
string ImgType = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
if (ImgType != ".png" && ImgType != ".jpg")
{
ClientScript.RegisterClientScriptBlock(GetType(), "", "<script>alert('图片格式不正确,请选择jpg或者png格式图片'); </script>");
}
else
{
string path = GetFileName() + ImgType;
FileUpload1.SaveAs(Server.MapPath("~/ClientBin") + "\\" + path);
imgUrl = "ClientBin" + "/" + path;
}
}
catch (Exception ex)
{
}
}
下面是生成文件名称的代码:
/// <summary>
/// 生成图片名称
/// </summary>
/// <returns></returns>
public static string GetFileName()
{
Random rd = new Random();
String serial = DateTime.Now.ToString("yyyyMMddHHmmss") + string.Format("{0, 000000}", rd.Next(100000, 999999).ToString());
return serial;
}
--------------------编程问答--------------------
gridview里弄一个image控件,路径='<%#Eval("url")%>'
--------------------编程问答--------------------
2楼的很详细了,3楼解释很到位,无奈 咱迟了
--------------------编程问答--------------------
不好意思 能把代码帖全吗?有好几个变量好像没定义
--------------------编程问答--------------------
前台
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server">选择图片:</asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="确定"
Width="66px" />
<br />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
<br />
<asp:Image ID="Image1" runat="server" Height="328px" Width="449px" />
<br />
</div>
</form>
</body>
后台
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (this.FileUpload1.PostedFile.FileName == "")
{
this.Label1.Text = "您还没有选择图片";
return;
}
else
{
string filepath = this.FileUpload1.PostedFile.FileName;
string filename = filepath.Substring(filepath.LastIndexOf("\\")+1);
string fileEX = filepath.Substring(filepath.LastIndexOf(".") + 1);
string serverpath = Server.MapPath("File/") + filename;
if (fileEX == "jpg" || fileEX == "bmp" || fileEX == "gif")
{
FileUpload1.PostedFile.SaveAs(serverpath);
Image1.ImageUrl = "File/" + filename;
Label1.Text = "上传成功!";
}
else
{
Label1.Text = "上传的图片扩展名错误!";
}
}
}
--------------------编程问答--------------------
往gridview里添加image控件后为什么在后台说imgurl没有定义呢
补充:.NET技术 , ASP.NET