?? upfile.cs
字號:
?using System;
using System.Collections.Generic;
using System.Text;
namespace Elysian
{
public class UpFile
{
//上傳文件C#代碼編寫
private string path = null;
private string fileType = null;
private int sizes = 0;
///
/// 初始化變量
///
public UpFile()
{
path = @"\pic\"; //上傳路徑
fileType = "jpg|gif|bmp";
sizes = 200; //傳文件的大小,默認200KB
}
public string Path
{
set
{
path = @"\" + value + @"\";
}
}
///
/// 設置上傳文件大小,單位為KB
///
public int Sizes
{
set
{
sizes = value * 1024;
}
}
///
/// 設置上傳文件的類型,如:jpg|gif|bmp ///
public string FileType
{
set
{
fileType = value;
}
}
///
/// 上傳圖片
///
/// 上傳控件名稱
/// true則以當前時間創建文件夾,false則為設置的文件夾
/// 返回上傳圖片的相對路徑
public string fileSaveAs(System.Web.UI.HtmlControls.HtmlInputFile name, bool creatDirectory)
{
try
{
string filePath = null;
//以當前時間修改圖片的名字或創建文件夾的名字
string modifyFileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
//獲得站點的物理路徑
string uploadFilePath = null;
//如果為true則以當前時間創建文件夾,否則為設置的文件夾
if (creatDirectory)
{
uploadFilePath = System.Web.HttpContext.Current.Server.MapPath(".") + @"\" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + @"\";
}
else
{
uploadFilePath = System.Web.HttpContext.Current.Server.MapPath(".") + path;
}
//獲得文件的上傳的路徑
string sourcePath = name.Value.Trim();
//判斷上傳文件是否為空
if (sourcePath == "" || sourcePath == null)
{
message("您沒有上傳數據呀,是不是搞錯了呀!");
return null;
}
//獲得文件擴展名
string tFileType = sourcePath.Substring(sourcePath.LastIndexOf(".") + 1);
//獲得上傳文件的大小
long strLen = name.PostedFile.ContentLength;
//分解允許上傳文件的格式
string[] temp = fileType.Split('|');
//設置上傳的文件是否是允許的格式
bool flag = false;
//判斷上傳文件大小
if (strLen >= sizes)
{
message("上傳的圖片不能大于" + sizes + "KB");
return null;
}
//判斷上傳的文件是否是允許的格式
foreach (string data in temp)
{
if (data == tFileType)
{
flag = true;
break;
}
}
//如果為真允許上傳,為假則不允許上傳
if (!flag)
{
message("目前本系統支持的格式為:" + fileType);
return null;
}
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(uploadFilePath);
//判斷文件夾否存在,不存在則創建
if (!dir.Exists)
{
dir.Create();
}
filePath = uploadFilePath + modifyFileName + "." + tFileType;
name.PostedFile.SaveAs(filePath);
filePath = path + modifyFileName + "." + tFileType;
return filePath;
}
catch
{
//異常
message("出現未知錯誤!");
return null;
}
}
private void message(string msg, string url)
{
System.Web.HttpContext.Current.Response.Write(" alert('" + msg + "');window.location='" + url + "'");
}
private void message(string msg)
{
System.Web.HttpContext.Current.Response.Write(" alert('" + msg + "'); ");
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -