用FileUpload控件,上傳圖片的例子如下:
首先申明使用命名空間。using System.IO;
在設(shè)計(jì)頁(yè)面拖進(jìn)一個(gè)input(File)控件,并把它作為服務(wù)器控件運(yùn)行。其ID為myFile;然后拖進(jìn)一個(gè)button,給button的單擊時(shí)間添加如下代碼:
view plaincopy to clipboardprint?
protected void submit_Click(object sender, EventArgs e)
{
string phName = this.txtName.Text;
string phType = this.ddlType.SelectedValue;
if (this.myFile.PostedFile != null)
{
string photoName1 = myFile.PostedFile.FileName; //獲取初始文件名
int i = photoName1.LastIndexOf("."); //取得文件名中最后一個(gè)"."的索引
string newext = photoName1.Substring(i); //獲取文件擴(kuò)展名
if (newext != ".gif" && newext != ".jpg"&&newext!=".jpeg" && newext != ".bmp" && newext != ".png")
{
Response.Write("文件格式不正確!");
Response.End();
}
DateTime now = DateTime.Now; //獲取系統(tǒng)時(shí)間
string photoName2 = now.Millisecond.ToString() + "_" + myFile.PostedFile.ContentLength.ToString() + newext; //重新為文件命名,時(shí)間毫秒部分+文件大小+擴(kuò)展名
myFile.PostedFile.SaveAs(Server.MapPath("photos" + photoName2)); // 保存文件到路徑,用Server.MapPath()取當(dāng)前文件的絕對(duì)目錄.在asp.net里"\"必須用""代替
}
}
protected void submit_Click(object sender, EventArgs e)
{
string phName = this.txtName.Text;
string phType = this.ddlType.SelectedValue;
if (this.myFile.PostedFile != null)
{
string photoName1 = myFile.PostedFile.FileName; //獲取初始文件名
int i = photoName1.LastIndexOf("."); //取得文件名中最后一個(gè)"."的索引
string newext = photoName1.Substring(i); //獲取文件擴(kuò)展名
if (newext != ".gif" && newext != ".jpg"&&newext!=".jpeg" && newext != ".bmp" && newext != ".png")
{
Response.Write("文件格式不正確!");
Response.End();
}
DateTime now = DateTime.Now; //獲取系統(tǒng)時(shí)間
string photoName2 = now.Millisecond.ToString() + "_" + myFile.PostedFile.ContentLength.ToString() + newext; //重新為文件命名,時(shí)間毫秒部分+文件大小+擴(kuò)展名
myFile.PostedFile.SaveAs(Server.MapPath("photos" + photoName2)); // 保存文件到路徑,用Server.MapPath()取當(dāng)前文件的絕對(duì)目錄.在asp.net里"\"必須用""代替
}
}
HtmlInputFile對(duì)象與HTML文件輸入元素對(duì)應(yīng)。你可用由id屬性指定的名稱來(lái)訪問(wèn)它。它有下列特性:
* PostedFile:上傳文件的內(nèi)容。
* Accept:以逗號(hào)界定的MIME類型列表,指定可能提交的文件類型。
* MaxLength:要提交的文件的最長(zhǎng)文件名長(zhǎng)度(包括路徑)。
* Size:用戶輸入/選擇上傳文件的文本框?qū)挾取?br>以下是HTML輸入控制的方法與特性:
* FileName:用戶計(jì)算機(jī)上的完全合格的文件名稱。它還包含上傳文件的本地路徑。
* ContentLength:上傳文件的大?。ㄗ止?jié))。
* ContentType:上傳文件的MIME內(nèi)容類型。
* InputStream:返回一個(gè)指向上傳文件的流(Stream)對(duì)象,允許你閱讀文件內(nèi)容。
* SaveAs:方便保存上傳文件的內(nèi)容。
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。