<asp:FileUpload /> 文件上传控件
实现一个简单的图片文件上传
//上传文件控件使用:实现上传图片功能,上传图片只能是jpg,gif,bmp三种类型,图片大小不超过60kb
后台代码:
view plaincopy to clipboardprint?
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
imgForFileUp.Visible = false;
}
}
protected void btUp_Click(object sender, EventArgs e)
{
bool isAllow = false; //是否允许上传,默认为false
string path = Server.MapPath("image/"); //上传文件保存路径 (相对路径)
if (fileUp.HasFile) //FileUpload控件不为空
{
string fileType = System.IO.Path.GetExtension(fileUp.FileName).ToLower(); //文件类型
string[] allowFile = { ".jpg", ".gif", ".bmp" };// 定义允许上传的文件类型
for (int i = 0; i < allowFile.Length; i++)
{
if ((fileType == allowFile[i]) && fileUp.PostedFile.ContentLength <= 60 * 1024)
{
isAllow = true; //设为true ,即允许上传
}
}
}
else
{
lbForFileUp.Text = "请上传文件!!!";
}
if (isAllow == true)
{
try
{
//以时间来重命名图片文件名
//string newName = DateTime.Now.ToFileTime() + "." + fileType;
//保存文件到服务器
fileUp.PostedFile.SaveAs(path + fileUp.FileName);
//提示信息
lbForFileUp.Text = "上传成功!!!";
//显示图片
imgForFileUp.ImageUrl = "image/" + fileUp.FileName;
imgForFileUp.Visible = true;
}
catch (HttpException ex)
{
lbForFileUp.Text = "上传失败:" + ex.Message.ToString();
}
}
else if (fileUp.PostedFile.ContentLength > 60 * 1024)
{
lbForFileUp.Text = "文件大小超过60KB!!!";
}
else
{
lbForFileUp.Text = "不可接受的文件类型!!!";
}
}
}