asp.net–檔案上傳

來源:互聯網
上載者:User
//判斷檔案類型是否符合標準
public static bool IsAllowedExtension(FileUpload hifile)
{
    System.IO.FileStream fs = new System.IO.FileStream(hifile.PostedFile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
    System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
    string fileclass = "";
    byte buffer;
    try
    {
        buffer = r.ReadByte();
        fileclass = buffer.ToString();
        buffer = r.ReadByte();
        fileclass += buffer.ToString();

    }
    catch
    {

    }
    r.Close();
    fs.Close();
    if (fileclass == "255216" || fileclass == "7173")//說明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
    {
        return true;
    }
    else
    {
        return false;
    }
}


/**//// <summary>
/// 儲存上傳的檔案
/// </summary>
/// <param name="fileType">要驗證的檔案類型</param>
/// <param name="lenghtKB">大小(單位:KB)</param>
/// <param name="filePath">儲存的路徑(絕對路徑)</param>
/// <param name="upLoad">上傳檔案的控制項</param>
/// <param name="fileName">成功:儲存後的檔案名稱.失敗:錯誤資訊</param>
/// <returns>是否儲存成功</returns>
public static bool SaveFile(string fileType, int lenghtKB, string filePath, FileUpload upLoad, out string fileName)
{
    //判斷是否上傳了檔案
    if (!upLoad.HasFile)
    {
        fileName = "無效的檔案內容";
        return false;
    }

    //判斷檔案大小
    if (upLoad.PostedFile.ContentLength > lenghtKB * 1024)
    {
        fileName = "檔案超過上傳大小";
        return false;
    }

    //檔案類型
    string type = upLoad.FileName;
    string last = type.Substring(type.LastIndexOf('.') + 1);
    type = upLoad.PostedFile.ContentType;
    //type = type.Substring(type.LastIndexOf('.') + 1);
    if (type.Substring(0, 5) != fileType)
    {
        fileName = "無效的檔案類型";
        return false;
    }

    DateTime date = DateTime.Now;

    //組建檔案名
    fileName = date.Year.ToString() + date.Month.ToString() + date.Day.ToString() + date.Hour.ToString() +
                date.Minute.ToString() + date.Second.ToString() + GetRandom().Next(0, 999) + "." + last;
    upLoad.SaveAs(filePath + @"\" + fileName);
    return true;

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.