那么使用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.注意文件上傳后的重名問題。
新聞熱點
疑難解答