在VS.NET下創(chuàng)建文件上載控件
2024-07-10 13:04:06
供稿:網(wǎng)友
在vs.net下創(chuàng)建文件上載控件
前言:
還記得在asp3.0里,我們?yōu)榱松陷d文件可真是煞費苦心,寫了一大堆的代碼,可執(zhí)行起來還是那么慢。但在asp.net里這個問題可以輕松搞定,這篇文章我們就探討如何建立一個用戶自定義的文件上載控件,并在我們的.aspx程序中使用它。
正文
第一步:開發(fā)自定義文件上載控件
打開vs.net,建立一個工程:webapp,我們使用webapp項目來做我們的工作。在項目webapp上點右健選擇add下的add web user control…,這時我們就可以建立一個用戶自定義控件():fileup.ascx,注意這個文件的擴展名是:.ascx。添加過程如下圖所示:
圖:添加用戶自定義控件
圖:添加用戶自定義控件
我們建立fileupload.ascx文件后,就可以象布置.html頁面一樣來設(shè)置布局。我們這個項目是要建立一個用戶自定義的文件上載控件,在一個上載控件中有三個必備的元素,從某種意義上講也可以說是“對象”:取得將要上載文件的htmlinputfile控件、保存文件名的textbox控件、按鈕button控件。我們可以使用vs.net的工具箱里的file field來直接添加它(看,vs.net充分考慮了我們的需求),并把它的runat屬性設(shè)為server,來告訴程序“我要在服務(wù)器上運行它”。為了體會asp.net為我們帶來的優(yōu)勢,我們使用服務(wù)器端web控件:textbox和button。控件的布局如下:
圖:控件布局
界面設(shè)計完成以后,我們需要進一步設(shè)置各個控件的屬性,主要有控件的id,text等,這里需要強調(diào)的關(guān)鍵有兩點:一是htmlinputfile控件的runat值:server;另外一個是form表單的enctype屬性:multipart/form-data,以支持多部分mime數(shù)據(jù)上載。fileupload.ascx文件的html代碼如下:
fileup.ascx
<%@ control language="c#" autoeventwireup="false" codebehind="fileup.ascx.cs" inherits="webapp.fileup"%>
<html>
<head>
</head>
<body>
<!-- add html content and server controls. do not add server
<form>
tags. -->
<form enctype="multipart/form-data" runat=server method=post id=form1>
<table cellspacing=1 cellpadding=1 width=400 border=0 height=151>
<tr>
selecte file to upload:
<input type=file id=filename runat="server" name="filename"/>
</td>
</tr>
<tr>
<td style="height: 27px">
save the name as:<asp:textbox id=txtsavename runat="server" height="24px" width="130px"></asp:textbox></td>
</tr>
<tr>
<td valign=center align=right>
<asp:button id=btnuplod runat="server" text="send file" height="24px" width="93px">
</asp:button>
</td>
</tr>
<tr>
<td valign=top>
<asp:label id=lblstatusc runat="server" height="33px" width="383px">
</asp:label>
</td>
</tr>
</table>
</form>
</body>
</html>
接下來,我們進行文件上載的處理工作。在.ascx頁面上我們雙擊button按鈕,或者右鍵文件名fileupload.ascx選擇view code,就可進入.ascs.cs文件,進行我們的編程工作。
asp.net為我們封裝了豐富的編程接口,減少了編程的工作量。并且,我們不需要知道這些接口內(nèi)部的工作原理,我們只要知道一個類的屬性、方法等的用法就能進行快速的開發(fā)。
asp.net為我們提供了一個system.web名字空間,system.web名字空間提供了基于browser/server系統(tǒng)的類和接口。我們的文件上載控件就要使用其中的httppostedfile類,所以我們首先了解httppostedfile類的一些相關(guān)的屬性和方法。
屬性:
contentlength 取得將要上載文件的字節(jié)數(shù),也就是文件的大小
contenttype 客戶端文件的mime類型
filename 上載文件的文件名
inputstream 建立一個stream對象,指向?qū)⒁x取文件的內(nèi)容
方法:
gettype 取得當(dāng)前實例的文件類型
saveas 把mime消息體作為文件保存在服務(wù)器
tostring 返回當(dāng)前對象的表現(xiàn)
熟悉以上的屬性和方法后,我們就開始開發(fā)我們的文件上載控件。為了便于讀者理解,我們首先看代碼,完整代碼如下:
fileup.ascx.cs:
namespace webapp
{
using system;
using system.io;
using system.data;
using system.drawing;
using system.web;
using system.web.ui.webcontrols;
using system.web.ui.htmlcontrols;
/// <summary>
/// summary description for fileup.
/// </summary>
public class fileup : system.web.ui.usercontrol
{
protected system.web.ui.webcontrols.button btnuplod;
protected system.web.ui.webcontrols.label lblstatusc;
protected system.web.ui.htmlcontrols.htmlinputfile filename;
protected system.web.ui.webcontrols.textbox txtsavename;
protected string uploadfolder = "c://temp//";
/// <summary>
///
/// </summary>
public fileup()
{
this.init += new system.eventhandler(page_init);
}
private void page_load(object sender, system.eventargs e)
{
// put user code to initialize the page here
}
private void page_init(object sender, eventargs e)
{
//
// codegen: this call is required by the asp.net web form designer.
//
initializecomponent();
}
#region web form designer generated code
/// required method for designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void initializecomponent()
{
this.btnuplod.click += new system.eventhandler(this.btnuplod_click);
this.load += new system.eventhandler(this.page_load);
}
#endregion
private void btnuplod_click(object sender, system.eventargs e)
{
if (txtsavename.text.tostring() =="")
{
lblstatusc.text = "沒有選擇另存為的文件名稱";
return;
}
if (filename.postedfile != null)
{
string strfileinfo = "file name: "+
filename.postedfile.filename +
"file type: "+
filename.postedfile.contenttype +
"file length:"+
filename.postedfile.contentlength ;
try
{
filename.postedfile.saveas("uploadfolder"+txtsavename.text.tostring());
lblstatusc.text = "file uploaded successfully:"+strfileinfo;
}
catch(exception ee)
{
lblstatusc.text = "file uploaded error:"+ee.tostring();
}
}
}
}
}
讓我們來逐行分析程序。
程序開始是一個名字空間的聲明:namespace webapp 這是系統(tǒng)根據(jù)項目自動生成的,我們可以手動更改它,或者刪除它,但作者不建議刪除名字空間,使用名字空間是一個良好的編程模式,便于以后的擴展工作。
using system;
using system.io;
using system.data;
using system.drawing;
using system.web;
using system.web.ui.webcontrols;
using system.web.ui.htmlcontrols;
上面的代碼為程序引入了我們需要的類,當(dāng)然如果不怕以后麻煩也可以不首先引用,而在使用每個類時都寫入名字空間。比如我們要使用剛才介紹的httppostedfile 類的postedfile.saveas方法,我們就要這樣寫了:system.web.ui.htmlcontrols.postedfile.saveas(),是不是很煩?
fileup : system.web.ui.usercontrol
說明fileup類繼承了system.web.ui.usercontrol類。
protected system.web.ui.webcontrols.button btnuplod;
protected system.web.ui.webcontrols.label lblstatusc;
protected system.web.ui.htmlcontrols.htmlinputfile filename;
protected system.web.ui.webcontrols.textbox txtsavename;
protected string uploadfolder = "c://temp//";
上面的代碼定義了btnuplod、lblstatusc等幾個實例。
下面我們著重分析btnuplod_click事件,當(dāng)用戶點擊“send file”按鈕時程序調(diào)用該事件。
if (txtsavename.text.tostring() =="")
{
lblstatusc.text = "沒有選擇另存為的文件名稱";
return;
}
這里檢驗用戶是否輸入了將要保存的文件名,如果沒有則返回。
if (filename.postedfile != null)
{
string strfileinfo = "file name: "+
filename.postedfile.filename +
"file type: "+
filename.postedfile.contenttype +
"file length:"+
filename.postedfile.contentlength ;
try
{
filename.postedfile.saveas("uploadfolder"+txtsavename.text.tostring());
lblstatusc.text = "file uploaded successfully:"+strfileinfo;
}
catch(exception ee)
{
lblstatusc.text = "file uploaded error:"+ee.tostring();
}
}
這段代碼在用戶已選擇了文件后才能執(zhí)行,strfileinfo保存了文件的相關(guān)信息,讀者可以看看httppostedfile類相關(guān)屬性的使用。使用try{…}catch{…}監(jiān)測程序,并輸出錯誤信息,使用saveas方法將文件保存到服務(wù)器。
到現(xiàn)在為止,我們已成功的建立了一個文件上載控件。那么在別的.aspx程序中使用它呢?
使用自定義文件上載控件
使用任何的自定義控件我們都需要使用 register 指令,相關(guān)用法這里就不做詳細的介紹了,讀者可以參考sdk熟悉它的用法。我們先看代碼:
controltest.aspx:
<%@ page language="c#" codebehind="controltest.aspx.cs" autoeventwireup="false" inherits="webapp.controltest" %>
<%@ register tagprefix="test" tagname="fileupload" src="fileup.ascx" %>
<html>
<head>
<meta content="microsoft visual studio 7.0" name=generator>
<meta content=c# name=code_language>
<meta content=jscript name=vs_defaultclientscript>
<meta content="internet explorer 5.0" name=vs_targetschema>
</head>
<body ms_positioning="gridlayout">
<test:con runat="server" id=con1>
</test:con>
</body>
</html>
你看:
<test:con runat="server" id=fielupload>
</test:con>
就這么簡單!需要提示的是在<test:con runat="server" id=fielupload></test:con>外面不能再有<form>標簽了,否則不能編譯成功。
好了,讓我們看一下我們的執(zhí)行結(jié)果吧!
圖:執(zhí)行結(jié)果
注:該程序在win2000+sdk(2728)環(huán)境下測試通過