protected void btnpic_upload_Click(object sender, EventArgs e)
{
#region 上傳文件
Boolean fileOk = false;
if (pic_upload.HasFile)//驗(yàn)證是否包含文件
{
//取得文件的擴(kuò)展名,并轉(zhuǎn)換成小寫(xiě)
string fileExtension = Path.GetExtension(pic_upload.FileName).ToLower();
//驗(yàn)證上傳文件是否圖片格式
fileOk = IsImage(fileExtension);
if (fileOk)
{
//對(duì)上傳文件的大小進(jìn)行檢測(cè),限定文件最大不超過(guò)8M
if (pic_upload.PostedFile.ContentLength 8192000)
{
string filepath = "~/Admin/I_Institution/Images/";
if (Directory.Exists(Server.MapPath(filepath)) == false)//如果不存在就創(chuàng)建file文件夾
{
Directory.CreateDirectory(Server.MapPath(filepath));
}
string virpath = filepath + CreatePasswordHash(pic_upload.FileName, 4) + fileExtension;//這是存到服務(wù)器上的虛擬路徑
string mappath = Server.MapPath(virpath);//轉(zhuǎn)換成服務(wù)器上的物理路徑
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!請(qǐng)重新選擇!";
}
}
else
{
lbl_pic.Visible = false;
pic.ImageUrl = "";
lbl_pic.Text = "要上傳的文件類(lèi)型不對(duì)!請(qǐng)重新選擇!";
}
}
else
{
lbl_pic.Visible = false;
pic.ImageUrl = "";
lbl_pic.Text = "請(qǐng)選擇要上傳的圖片!";
}
#endregion
}
/// summary>
/// 驗(yàn)證是否指定的圖片格式
/// /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" };
//對(duì)上傳的文件的類(lèi)型進(jìn)行一個(gè)個(gè)匹對(duì)
for (int i = 0; i allowExtension.Length; i++)
{
if (thestr == allowExtension[i])
{
isimage = true;
break;
}
}
return isimage;
}
/// summary>
/// 創(chuàng)建一個(gè)指定長(zhǎng)度的隨機(jī)salt值
/// /summary>
public string CreateSalt(int saltLenght)
{
//生成一個(gè)加密的隨機(jī)數(shù)
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[saltLenght];
rng.GetBytes(buff);
//返回一個(gè)Base64隨機(jī)數(shù)的字符串
return Convert.ToBase64String(buff);
}
/// summary>
/// 返回加密后的字符串
/// /summary>
public string CreatePasswordHash(string pwd, int saltLenght)
{
string strSalt = CreateSalt(saltLenght);
//把密碼和Salt連起來(lái)
string saltAndPwd = String.Concat(pwd, strSalt);
//對(duì)密碼進(jìn)行哈希
string hashenPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "sha1");
//轉(zhuǎn)為小寫(xiě)字符并截取前16個(gè)字符串
hashenPwd = hashenPwd.ToLower().Substring(0, 16);
//返回哈希后的值
return hashenPwd;
}
tr>
td height="25" width="30%" align="right">
機(jī)構(gòu)圖標(biāo)路徑 :
/td>
td height="25" width="*" align="left">
asp:Image ID="pic" runat="server" Width="200px" Visible="False" />br />
asp:FileUpload ID="pic_upload" runat="server" />
asp:Button ID="btnpic_upload" runat="server" Text="圖片開(kāi)始上傳" OnClick="btnpic_upload_Click" />br />
asp:Label ID="lbl_pic" runat="server" Text="" Visible="False">/asp:Label>
/td>
/tr>