標籤:
public class ProcessUpload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//1.擷取使用者上傳的檔案
if (context.Request.Files.Count > 0)
{
//擷取第一個檔案域中上傳上來的檔案
HttpPostedFile fileData = context.Request.Files[0];
//判斷上傳上來的檔案位元組數是否大於0
if (fileData.ContentLength > 0)
{
string ext = Path.GetExtension(fileData.FileName);
if ((ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif" || ext == ".bmp") && fileData.ContentType.ToLower().StartsWith("image"))
{
#region 計算檔案名稱和目錄,儲存檔案
//通過guid+舊檔案名稱,計算得到一個新的檔案名稱
string new_fileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(fileData.FileName);
//擷取當前new_fileName的雜湊碼,就是一個整數。
int hash_code = new_fileName.GetHashCode();
//2.使用該整數和二進位值"1111"(也就是16進位值:0xf)與,擷取當前整數的最後4為值。
int dir1 = hash_code & 0xf;//第一層目錄
//任何類都是繼承自object類。object類中有一個方法GetHashCode(),擷取當前對象的雜湊碼。
//將原始的hash_code值向右移動4位。、
hash_code = hash_code >> 4;
int dir2 = hash_code & 0xf;//得到了第二層目錄
//路徑拼接
string targetFilePath = Path.Combine(context.Request.MapPath("upload/"), dir1.ToString(), dir2.ToString());
//判斷當前檔案夾是否存在,如果不存在則建立檔案夾
if (!Directory.Exists(targetFilePath))
{
Directory.CreateDirectory(targetFilePath);
}
//2.將使用者上傳的檔案另存新檔到伺服器的目錄下。
//將檔案名稱與目錄拼接。
targetFilePath = Path.Combine(targetFilePath, new_fileName);
fileData.SaveAs(targetFilePath);
#endregion
context.Response.Write("檔案上傳成功!");
}
else
{
context.Response.Write("非法的檔案!");
}
}
}
}
asp.net上傳檔案