|
功能描述: 用户在选择了要上传的图片之后,点击——上传,下面便显示该图片的名称和图像。
这里css.css是引用的外部样式表,只用到了一个按钮样式,具体样式为:
.btn {
BORDER-RIGHT: #7b9ebd 1px solid; PADDING-RIGHT: 2px; BORDER-TOP: #7b9ebd 1px solid; PADDING-LEFT: 2px; FONT-SIZE: 12px; FILTER: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr=#ffffff, EndColorStr=#cecfde); BORDER-LEFT: #7b9ebd 1px solid; CURSOR: hand; COLOR: black; PADDING-TOP: 2px; BORDER-BOTTOM: #7b9ebd 1px solid
}
后台详细代码为:
static string newFileName;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string[] str=upFile();
foreach(string s in str)
{
this.lblShowImg.Text = s;
}
imgShowImg.ImageUrl = "~/uploadFiles/" + this.lblShowImg.Text;
}
private string[] upFile()
{
int maxSize = 1024 * 1024 * 10; //规定最大上传的大小为10MB;
string path = Server.MapPath("~/uploadFiles/");
string[] info = new string[2];
string Msg = "";
bool flag = false;
///获取文件的大小(kb)
int fileSize = Convert.ToInt32(this.FileUpload1.PostedFile.ContentLength / 1024);
string fileName = FileUpload1.PostedFile.FileName;
int intEx = fileName.LastIndexOf(".") + 1;
string strEx = fileName.Substring(intEx);
newFileName = AutoFileName() + "." + strEx; //新文件名
if (fileSize > 0)
{
//有文件上传
if (fileSize > maxSize)
{
Msg = "上传的文件超过了允许上传的大小";
flag = true;
}
if (!chkEx(strEx))
{
Msg += "\n上传的文件不是所允许上传的文件类型!";
flag = true;
}
}
else
{
Msg += "无文件,请选择文件上传!";
flag = true;
}
if (!flag)
{
try
{
FileUpload1.SaveAs(path + newFileName);
Msg = "上传成功!";
info[0] = Msg;
info[1] = newFileName;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
else
{
info[0] = Msg;
info[1] = "";
}
return info;
}
/// <summary>
/// 生成一个随机数
/// </summary>
/// <returns></returns>
private string AutoFileName()
{
string strNewName = System.DateTime.Now.Year.ToString()
+ System.DateTime.Now.Month.ToString()
+ System.DateTime.Now.Day.ToString()
+ System.DateTime.Now.Hour.ToString()
+ System.DateTime.Now.Minute.ToString()
+ System.DateTime.Now.Second.ToString()
+ System.DateTime.Now.Millisecond.ToString();
Random rd = new Random();
strNewName += rd.Next(1000, 9999);
return strNewName;
}
/// <summary>
/// 检查上传文件的后缀名是否在允许上传的范围内
/// </summary>
/// <param name="StrEx"></param>
/// <returns></returns>
private bool chkEx(string StrEx)
{
string fileEx = "jpg/gif/bmp";
bool flag = false;
string[] AllowEx = fileEx.Split('/');
for (int i = 0; i < AllowEx.Length; i++)
{
if (StrEx.ToLower() == AllowEx.ToLower())
{
flag = true;
break;
}
}
return flag;
}
}
|
|