protected void Button2_Click(object sender, EventArgs e)
{
//禁止上传0字节的文件、禁止上传文件名为空的文件
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "" && FileUpload1.PostedFile.ContentLength != 0)
{
try
{
//限制文件大小不能超过10MB,需要在web.config文件设置<httpRuntime maxRequestLength="1024" />不然下面的代码会报错
if (FileUpload1.PostedFile.ContentLength > 1 * 1024 * 1024)
{
lblMessage.Text = "上传文件最大不能超过1MB";
return;
}
//限制可上传的文件类型
string strFileName = Path.GetExtension(FileUpload1.PostedFile.FileName).ToUpper();
if (!(strFileName == ".RAR" || strFileName == ".XLSX" || strFileName == ".JPG" || strFileName == ".DOCX"))
{
lblMessage.Text = "禁止上传非法的文件类型";
return;
}
//上传同名文件不会被覆盖(采用时间戳+四位随机码标识服务器的文件名称)
Random ran = new Random();
string sNewImg = DateTime.Now.ToString(@"yyyyMMddHHmmss") + ran.Next(1000, 9999) + Path.GetExtension(FileUpload1.PostedFile.FileName);
//保存文件到服务器指定的文件夹
string sPath = Server.MapPath("~/Files/" + sNewImg);
//如果不存在指定的文件夹,则创建指定的文件夹
if (!Directory.Exists(Path.GetDirectoryName(sPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(sPath));
}
FileUpload1.PostedFile.SaveAs(sPath);
lblMessage.Text = "文件上传成功";
}
catch (Exception ex)
{
lblMessage.Text = "发生错误:" + ex.Message.ToString();
}
}
}