/*
Descript:上傳檔案
Author:Blue.Dream
Date:2004-09-21 22:21
聲明:最近發現不少網站引用本人的文章,竟將作者資訊都省略了,請引用本文的網站將作者不要省略作者的資訊.
*/
namespace BDStudio.Common
{
using System;
using System.IO;
using System.Web;
/// <summary>
/// 上傳單個檔案
/// </summary>
public class UpLoadFile
{
private string[] AllowFileType; //所允許的檔案類型
private double FileLength; //所允許的檔案大小(KB)
private string SavePath; //檔案的儲存路徑
private string SaveFile; //上傳後的檔案名稱
private string Error; //儲存錯誤資訊
private string FileExtesion; //上傳檔案的副檔名
/// <summary>
/// 建構函式
/// </summary>
/// <param name="allFileType">允許的檔案類型,多個以","分開</param>
/// <param name="fileLength">檔案大小</param>
/// <param name="savePath">儲存路徑</param>
public UpLoadFile(string allFileType,double fileLength,string savePath)
{
char[] sp = {','};
AllowFileType = allFileType.Split(sp);
FileLength = fileLength;
SavePath = savePath;
}
/// <summary>
/// 返回產生的檔案名稱
/// </summary>
public string FileName
{
get
{
return SaveFile;
}
}
/// <summary>
/// 返回出錯資訊
/// </summary>
public string ErrorMessage
{
get
{
return Error;
}
}
/// <summary>
/// 根據SavePath,組建檔案名
/// </summary>
/// <returns></returns>
private string MakeFileName(string fileType)
{
string file = this.SavePath + "//" + System.DateTime.Now.Year.ToString()+System.DateTime.Now.Month.ToString()+System.DateTime.Now.Day.ToString()+System.DateTime.Now.Hour.ToString()+System.DateTime.Now.Minute.ToString()+System.DateTime.Now.Second.ToString()+this.FileExtesion;
for(; File.Exists(file);)
{
file = this.SavePath + "//" + System.DateTime.Now.Year.ToString()+System.DateTime.Now.Month.ToString()+System.DateTime.Now.Day.ToString()+System.DateTime.Now.Hour.ToString()+System.DateTime.Now.Minute.ToString()+System.DateTime.Now.Second.ToString()+this.FileExtesion;
}
return file;
}
/// <summary>
/// 檢查檔案類型
/// </summary>
/// <param name="fileEx">MIME內容</param>
/// <returns></returns>
private bool CheckFileExt(string fileEx)
{
bool result = false;
for(int i = 0; i < this.AllowFileType.Length; i++)
{
if(fileEx.IndexOf(this.AllowFileType[i].ToLower()) > -1)
{
result = true;
break;
}
}
return result;
}
public bool UpLoad()
{
bool result = true;
System.Web.HttpFileCollection objFiles = System.Web.HttpContext.Current.Request.Files;
System.Web.HttpPostedFile objFile = objFiles[0];
try
{
//查看檔案長度
if(objFile.ContentLength > (this.FileLength))
{
this.Error = "檔案大小超出範允許的範圍!";
return false;
}
string fileName = Path.GetFileName(objFile.FileName);
this.FileExtesion = Path.GetExtension(fileName);
if(!CheckFileExt(this.FileExtesion.ToLower()))
{
this.Error = "檔案類型"+this.FileExtesion+"不允許!";
return false;
}
//取得要儲存的檔案名稱
string UpFile = this.MakeFileName(this.FileExtesion);
//儲存檔案
objFile.SaveAs(UpFile);
//返迴文件名
this.SaveFile = Path.GetFileName(UpFile);
}
catch(Exception e)
{
result = false;
this.Error = e.Message;
}
return result;
}
}
}
http://blog.csdn.net/zhgroup