asp.net上傳檔案

來源:互聯網
上載者:User

標籤:

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上傳檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.