protected void btnpic_upload_Click(object sender, EventArgs e)
{
#region 上传文件
Boolean fileOk = false;
if (pic_upload.HasFile)
{
string fileExtension = Path.GetExtension(pic_upload.FileName).ToLower();
fileOk = IsImage(fileExtension);
if (fileOk)
{
if (pic_upload.PostedFile.ContentLength < 8192000)
{
string filepath = "~/Admin/I_Institution/Images/";
if (Directory.Exists(Server.MapPath(filepath)) == false)
{
Directory.CreateDirectory(Server.MapPath(filepath));
}
string virpath = filepath + CreatePasswordHash(pic_upload.FileName, 4) + fileExtension;
string mappath = Server.MapPath(virpath);
pic.Visible = true;
pic_upload.PostedFile.SaveAs(mappath);
pic.ImageUrl = virpath;
lbl_pic.Visible = true;
lbl_pic.Text = "上传成功";
}
else
{
pic.Visible = false;
lbl_pic.Visible = true;
pic.ImageUrl = "";
lbl_pic.Text = "文件大小超出8M!请重新选择!";
}
}
else
{
lbl_pic.Visible = false;
pic.ImageUrl = "";
lbl_pic.Text = "要上传的文件类型不对!请重新选择!";
}
}
else
{
lbl_pic.Visible = false;
pic.ImageUrl = "";
lbl_pic.Text = "请选择要上传的图片!";
}
#endregion
}
/// <summary>
/// 验证是否指定的图片格式
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public bool IsImage(string str)
{
bool isimage = false;
string thestr = str.ToLower();
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);
return Convert.ToBase64String(buff);
}
/// <summary>
/// 返回加密后的字符串
/// </summary>
public string CreatePasswordHash(string pwd, int saltLenght)
{
string strSalt = CreateSalt(saltLenght);
string saltAndPwd = String.Concat(pwd, strSalt);
string hashenPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "sha1");
hashenPwd = hashenPwd.ToLower().Substring(0, 16);
return hashenPwd;
}