欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net HTML文件上传标签

程序员文章站 2023-11-13 08:28:28
微软提供的控件//www.jb51.net/codes/9709.html 前台 <%@ page language="c#" autoeventwireup="tr...
微软提供的控件//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;
}