protected void BtnPicUpLoad_up_Click(object sender, EventArgs e)
{
Boolean fileOk = false;
if (FileUpload2.HasFile)//验证是否包含文件
{
//取得文件的扩展名,并转换成小写
string fileExtension = Path.GetExtension(FileUpload2.FileName).ToLower();
//验证上传文件是否图片格式
fileOk = IsImage(fileExtension);
if (fileOk)
{
//对上传文件的大小进行检测,限定文件最大不超过8M
if (FileUpload2.PostedFile.ContentLength < 8192000)
{
string filepath = "../../upload/";
if (Directory.Exists(Server.MapPath(filepath)) == false)//如果不存在就创建file文件夹
{
Directory.CreateDirectory(Server.MapPath(filepath));
}
string virpath = filepath + CreatePasswordHash(FileUpload2.FileName, 4) + fileExtension;//这是存到服务器上的虚拟路径
string mappath = Server.MapPath(virpath);//转换成服务器上的物理路径
FileUpload2.PostedFile.SaveAs(mappath);//保存图片
//显示图片
hidUPFilePathList_up.Value += "," + virpath;//隐藏域id
//hidUPFilePathList.Value += "," + mappath;
string[] filelist = hidUPFilePathList_up.Value.Split(',');
UPFileListDiv_up.InnerHtml = string.Empty;//UPFileListDiv_up---div的id
foreach (string picpath in filelist)
{
if (!string.IsNullOrEmpty(picpath))
{
//Img_pic.ImageUrl = virpath;
UPFileListDiv_up.InnerHtml += string.Format("<span value='{0}'><img src="{0}" style=" 100px;margin:15px 10px"><a style="color:red;margin-left:0px; margin-right:0px;text-decoration:none;cursor:pointer;" onclick="deleteUpFile_up(this)"> × </a></span>", picpath);
}
}
//清空提示
Label_up.Text = "";
}
else
{
Image_up.ImageUrl = "";
Label_up.Text = "文件大小超出8M!请重新选择!";
}
}
else
{
Image_up.ImageUrl = "";
Label_up.Text = "要上传的文件类型不对!请重新选择!";
}
}
else
{
Image_up.ImageUrl = "";
Label_up.Text = "请选择要上传的图片!";
}
}
/// <summary>
/// 验证是否指定的图片格式
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public bool IsImage(string str)
{
bool isimage = false;
string thestr = str.ToLower();
//限定只能上传jpg和gif图片
string[] allowExtension = { ".jpg", ".gif", ".bmp", ".png" };
//对上传的文件的类型进行一个个匹对
for (int i = 0; i < allowExtension.Length; i++)
{
if (thestr == allowExtension[i])
{
isimage = true;
break;
}
}
return isimage;
}
/// <summary>
/// 创建一个指定长度的随机salt值
/// </summary>
public string CreateSalt(int saltLenght)
{
//生成一个加密的随机数
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[saltLenght];
rng.GetBytes(buff);
//返回一个Base64随机数的字符串
return Convert.ToBase64String(buff);
}
/// <summary>
/// 返回加密后的字符串
/// </summary>
public string CreatePasswordHash(string pwd, int saltLenght)
{
string strSalt = CreateSalt(saltLenght);
//把密码和Salt连起来
string saltAndPwd = String.Concat(pwd, strSalt);
//对密码进行哈希
string hashenPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "sha1");
//转为小写字符并截取前16个字符串
hashenPwd = hashenPwd.ToLower().Substring(0, 16);
//返回哈希后的值
return hashenPwd;
}