文件上传
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
//判断文件大小是否大于10MB
if (FileUpload1.PostedFile.ContentLength < 10485760)
{
if (CheckFileType())
{
try
{
/*使用时间戳精确到毫秒,SessionID,上传文件大小,
5位随机数,来做上传文件名唯一性的处理*/
/* Random rd = new Random();
String fileName = DateTime.Now.ToString("yyyyMMddhhmmssfff")+
rd.Next(10000,99999)+
Session.SessionID +
FileUpload1.PostedFile.ContentLength +
System.IO.Path.GetExtension(FileUpload1.FileName);*/
//string fileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(FileUpload1.FileName);
/*如果使用时间戳还觉得不够保险,需要绝对唯一
*那么可以使用GUID(全局的唯一标示符):*/
String fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + System.IO.Path.GetExtension(FileUpload1.FileName);
string fileSaveFullPath = Server.MapPath("/uploadFiles/") + fileName;
if (System.IO.File.Exists(fileSaveFullPath))
{
lblMessage.Text = "Sorry,the file has existed,please wait for a while to upload!";
return;
}
FileUpload1.PostedFile.SaveAs(fileSaveFullPath);
lblMessage.Text = "upload success!";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "redirect", "window.location = window.location;alert('file upload success!')", true);
}
catch (Exception)
{
lblMessage.Text = "Exception is appear!";
}
}
else
{
lblMessage.Text = "sorry,it not allow filename extension !";
}
}
else
{
lblMessage.Text = "Sorry,Your file IS beyond 10MB!";
}
}
else
{
lblMessage.Text = "Please select a available file!!!";
}
}
//通过读取文件二进制的前两个字节判断文件的类型
private bool CheckFileType()
{
//得到客户端文件的绝对路径
String file = FileUpload1.PostedFile.FileName;
//创建文件流.
System.IO.FileStream fs = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read);
//创建读取文件二进制的对象
System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
string fileType = String.Empty;
//读取文件的第一个字节,并将读取位置提升一个字节.
fileType = br.ReadByte().ToString();
//读取第二个字节,并将读取位置提升一个字节.
fileType += br.ReadByte().ToString();
/*如果不知道文件的二进制前两个字节,可以将它打印出来:
Response.Write(fileType);
*/
Response.Write(fileType);
System.Collections.Hashtable tmphastable = new System.Collections.Hashtable();
tmphastable.Add("jpg","25516");
tmphastable.Add("png","13780");
tmphastable.Add("gif", "7173");
tmphastable.Add("bmp", "6677");
tmphastable.Add("Excel,word,ppt", "208207");
tmphastable.Add("Access", "01");
tmphastable.Add("zip", "8075");
tmphastable.Add("rar", "8297");
tmphastable.Add("txt", "115115");
tmphastable.Add("swf", "6787");
// tmphastable.Add("", "");
// tmphastable.Add("", "");
// tmphastable.Add("", "");
// tmphastable.Add("", "");
// tmphastable.Add("", "");
//允许上传文件的扩展名
bool flag = false;
foreach( DictionaryEntry tmpDE in tmphastable)
{
if (tmpDE.Value.ToString() == fileType.ToString())
{
flag = true;
}
}
return flag;
}