代码实现了简单的图片上传功能(改一下也可以上传其他的),没有做图片大小和格式的判断,主要是熟悉fileupload控件
界面代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="WebApplication2.WebForm3" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<asp:Button ID="Button1" runat="server" Text="上传" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<br />
<asp:Image ID="Image1" runat="server" visible="false" />
<br />
</div>
</form>
</body>
</html>
后台代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile) //判断是否上传了文件
{
string savePath = Server.MapPath("~/upload/");//指定上传文件在服务器上的保存路径
//检查服务器上是否存在这个物理路径,如果不存在,则创建
if (!System.IO.Directory.Exists(savePath))
{
//对该路径应该有足够的权限,否则报错
System.IO.Directory.CreateDirectory(savePath);
}
savePath = savePath + "\\" + FileUpload1.FileName;
FileUpload1.SaveAs(savePath); //保存文件
Label1.Text = string.Format("<a href='upload/{0}'>upload/{0}</a>", FileUpload1.FileName);
Image1.Visible = true;
Image1.ImageUrl = "~/upload/" + FileUpload1.FileName;
}
}
}
}
其中,特别要注意的是文件路径问题,就是我最后刺耳的image1的url地址。,要使用相对路径