asp.net HTML檔案上傳標籤

來源:互聯網
上載者:User

微軟提供的控制項http://www.jb51.net/codes/9709.html
前台
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>html檔案上傳標籤</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="File1" type="file" runat="server" />
<asp:Button ID="btn_up" runat="server" Text="上傳" OnClick="btn_up_Click" />
</div>
</form>
</body>
</html>
後台
protected void btn_up_Click(object sender, EventArgs e)
{
string spath = Server.MapPath("~/test/");
string filename = File1.PostedFile.FileName;
int idx = filename.LastIndexOf(@"\");
string shortname = filename.Substring(idx + 1);//獲得檔案名稱
this.File1.PostedFile.SaveAs(spath + shortname);
}
end
官方給出的使用方法:
需要在要目錄下建立兩個目錄:upfile和upimg
添加一個FileUpload控制項.一個Button.一個Image.一個Label

關鍵代碼:
string name = FileUpload1.FileName;//獲得上傳檔案的名字.
string size = FileUpload1.PostedFile.ContentLength.ToString();//檔案大小.
string type = FileUpload1.PostedFile.ContentType;//檔案類型.
string type2 = name.Substring(name.LastIndexOf(".") + 1);//LastIndexOf()最後一個索引位置匹配.Substring()裡面的+1是重載.
string ipath = Server.MapPath("upimg") + "\\" + name;//取得根目錄下面的upimg目錄的路徑.
string fpath = Server.MapPath("upfile") + "\\" + name;
string wpath = "upimg\\" + name;//獲得虛擬路徑.
if (type2 == "jpg" || type2 == "gif" || type2 == "bmp" || type2 == "png")
{
FileUpload1.SaveAs(ipath);//儲存方法,參數是一個地址字串.
Image1.ImageUrl = wpath;
Label1.Text = "你傳的檔案名稱是:" + name + "<br>檔案大小為:" + size + "位元組<br>檔案類型是:" + type +
"<br>尾碼是:" + type2 + "<br>實際路徑是:" + ipath + "<br>虛擬路徑是:" + fpath;
Image1.Visible = true;
}
else
{
Image1.Visible = false;
FileUpload1.SaveAs(fpath);
Label1.Text = "你傳的檔案名稱是:" + name + "<br>檔案大小為:" + size + "位元組<br>檔案類型是:" + type +
"<br>尾碼是:" + type2 + "<br>實際路徑是:" + ipath + "<br>虛擬路徑是:" + fpath;
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.