using system;
namespace upfile { ///
/// upfile 的摘要說明。
///
public class upfile
{
private string path = null;
private string filetype = null;
private int sizes = 0;
///
/// 初始化變量
///
public upfile()
{
path = @"/uploadimages/"; //上傳路徑
filetype = "jpg|gif|bmp";
sizes = 200; //傳文件的大小,默認200kb
}
///
/// 設置上傳路徑,如:uploadimages/
///
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+"'); ");
}
}
}
--------------------------------------------------------------------------------
冬天來了,春天還會遠嗎
i still believe ,some day you and me.
--------------------------------------------------------------------------------
1. c#實現web文件的上傳
在web編程中,我們常需要把一些本地文件上傳到web服務器上,上傳后,用戶可以通過瀏覽器方便地瀏覽這些文件,應用十分廣泛。
那么使用c#如何實現文件上傳的功能呢?下面筆者簡要介紹一下。
首先,在你的visual c# web project 中增加一個上傳用的web form,為了要上傳文件,需要在toolbox中選擇html類的file field控件,將此控件加入到web form中,然而此時該控件還不是服務端控件,我們需要為它加上如下一段代碼:<input id=uploadfile1 type=file size=49 runat="server">,這樣它就成為服務端控件了,如果需要同時上傳數個文件時,我們可以相應增加此控件。
需要注意的是代碼中一定要把<form>的屬性設置成為:
<form method=post enctype=multipart/ form-data runat="server">
如果沒有這個屬性,就不能實現上傳。
然后在此web form中增加一個web form類的button,雙擊button添加如下代碼:
//上傳圖片的程序段
datetime now = datetime.now ;
//取現在時間到datatime類的對象now中
string strbaselocation = "d://web//fc//pic//";
//這是文件將上傳到的服務器的絕對目錄
if (uploadfile1.postedfile.contentlength != 0) //判斷選取對話框選取的文件長度是否為0
{
uploadfile1.postedfile.saveas(strbaselocation+now.dayofyear.tostring()+uploadfile1.postedfile.contentlength.tostring()+".jpg");
//執行上傳,并自動根據日期和文件大小不同為文件命名,確保不重復
label1.text="圖片1已經上傳,文件名為:"+now.dayofyear.tostring()+uploadfile1.postedfile.contentlength.tostring()+".jpg";
navigator.insert(system.xml.treeposition.after, xmlnodetype.element,"pic1","","") ;
navigator.insert(system.xml.treeposition.firstchild, xmlnodetype.text,"pic1","","") ;
navigator.value= now.dayofyear.tostring()+uploadfile1.postedfile.contentlength.tostring()+".jpg" ;
navigator.movetoparent() ;
}
上面的代碼用于筆者開發的一個使用xml文件存儲新聞信息的系統中,后面幾句代碼作用是寫上傳文件信息到xml文件中。如果要上傳其他類型文件,只需要將jpg改為相應類型的后綴名即可,如改為doc即可上傳word文件,瀏覽器即可直接瀏覽上傳的word文件。
【注意事項】
1. 上傳文件不可以無限大;
2. 要注意iis的安全性方面的配合;
3. 用visual studio 的安裝項目做安裝程序的時候,請注意安裝程序所在的絕對路徑問題;
4. 注意文件上傳后的重名問題。
--------------------------------------------------------------------------------
2. c#實現web文件的上傳
using system;
using system.data;
using system.data.sqlclient;
using system.web.ui.htmlcontrols;
using system.drawing.imaging;
using system.configuration;
using system.drawing;
namespace zhuanti
{
/// <summary>
/// 這是一個用于玩家投稿中實現玩家上傳文件功能中用到的相應的函數的功能模塊
/// </summary>
public class fileupload
{
public enum file //定義一個人用于存放玩家上傳文件信息的一個數組
{
file_size , //大小
file_postname, //類型(文件后綴名)
file_sysname , //系統名
file_orginname, //原來的名字
file_path //文件路徑
}
private static random rnd = new random(); //獲取一個隨機數
public static string[] uploadfile(htmlinputfile file,string upload_dir) //實現玩家文件上傳功能的主函數
{
string[] arr = new string[5];
string filename = getuniquelystring(); //獲取一個不重復的文件名
string fileorginname = file.postedfile.filename.substring
(file.postedfile.filename.lastindexof("http://")+1);//獲取文件的原始名
if(file.postedfile.contentlength<=0)
{ return null; }
string postfilename;
string filepath = upload_dir.tostring();
string path = filepath + "http://";
try
{
int pos = file.postedfile.filename.lastindexof(".")+1;
postfilename = file.postedfile.filename.substring(pos,file.postedfile.filename.length-pos);
file.postedfile.saveas(path+filename+"."+postfilename); //存儲指定的文件到指定的目錄
}
catch(exception exec)
{
throw(exec);
}
double unit = 1024;
double size = math.round(file.postedfile.contentlength/unit,2);
arr[(int)file.file_size] = size.tostring(); //文件大小
arr[(int)file.file_postname] = postfilename; //文件類型(文件后綴名)
arr[(int)file.file_sysname] = filename; //文件系統名
arr[(int)file.file_orginname] = fileorginname; //文件原來的名字
arr[(int)file.file_path]=path+filename+"."+postfilename; //文件路徑
return arr;
}
public static bool operatedb(string sqlstr) //建立一個和數據庫的關聯
{
if (sqlstr==string.empty)
return false;
sqlconnection myconnection = new sqlconnection(configurationsettings.appsettings["connstring"]);
sqlcommand mycommand = new sqlcommand(sqlstr, myconnection);
myconnection.open();
mycommand.executenonquery();
myconnection.close();
return true;
}
public static string getuniquelystring() //獲取一個不重復的文件名
{
const int random_max_value = 1000;
string strtemp,stryear,strmonth,strday,strhour,strminute,strsecond,strmillisecond;
datetime dt =datetime.now;
int rndnumber = rnd.next(random_max_value);
stryear = dt.year.tostring ();
strmonth = (dt.month > 9)? dt.month.tostring() : "0" + dt.month.tostring();
strday = (dt.day > 9)? dt.day.tostring() : "0" + dt.day.tostring();
strhour = (dt.hour > 9)? dt.hour.tostring() : "0" + dt.hour.tostring();
strminute = (dt.minute > 9)? dt.minute.tostring() : "0" + dt.minute.tostring();
strsecond = (dt.second > 9)? dt.second.tostring() : "0" + dt.second.tostring();
strmillisecond = dt.millisecond.tostring();
strtemp = stryear + strmonth + strday +"_"+ strhour + strminute + strsecond +"_"+ strmillisecond +"_"+ rndnumber.tostring () ;
return strtemp;
}
}
}
新聞熱點
疑難解答