asp.net 單文件上傳的方法

 /// <summary>
    /// 文件上傳
    /// </summary>
    /// <param name="upload">上傳控件</param>
    /// <param name="strFolder">是否指定上傳的文件保存在那個文件夾下,可以為空</param>
    /// <param name="strNewFileName">是否自定義上傳的文件名稱,可以為空</param>
    /// <param name="b">b為true使用默認文件名上傳,否則會被自動重命名</param>
    /// <returns>上傳成功返回文件名+上一級目錄,否則返回空</returns>

    public static string UploadFile(FileUpload upload,string strFolder,string strNewFileName,bool b)
    {
        string strFileName = upload.FileName;
        int pos = strFileName.LastIndexOf(".");
        string strFormat = strFileName.Substring(pos + 1);
        DateTime dNow = DateTime.Now;
        string strDir = dNow.ToString("yyyyMM");
        string strRootPath = "";
        if (!string.IsNullOrEmpty(strFolder))
            strRootPath = UploadPath + strFolder + @"/" + strDir + @"/"; //UploadPath 爲上傳文件的根目錄,如:C:/Users/lz_wu/MyProject/
        else
            strRootPath = UploadPath + strDir + @"/";
        if (!Directory.Exists(strRootPath))
            Directory.CreateDirectory(strRootPath);
        string newFileName = "";
        if (b == false)
        {
            if (!string.IsNullOrEmpty(strNewFileName))
                newFileName = strNewFileName.Trim() + "." + strFormat;//默認上傳的文件名
            else
                newFileName = dNow.ToString("yyyyMMddHHmmss") + "." + strFormat;//默認上傳的文件名
        }
        else
            newFileName = strFileName;
        try
        {
            upload.PostedFile.SaveAs(strRootPath + newFileName);
            return strDir+@"/"+newFileName;
        }
        catch { return ""; }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章