您的位置:首页 > 编程语言 > ASP

asp.net上传文件代码

2010-07-17 14:58 381 查看
首先申明使用命名空间。using System.IO;
在设计页面拖进一个input(File)控件,并把它作为服务器控件运行。其ID为myFile;然后拖进一个button,给button的单击时间添加如下代码:
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("."); //取得文件名中最后一个"."的索引
string newext = photoName1.Substring(i); //获取文件扩展名
if (newext != ".gif" && newext != ".jpg"&&newext!=".jpeg" && newext != ".bmp" && newext != ".png")
{
Response.Write("文件格式不正确!");
Response.End();
}
DateTime now = DateTime.Now; //获取系统时间
string photoName2 = now.Millisecond.ToString() + "_" + myFile.PostedFile.ContentLength.ToString() + newext; //重新为文件命名,时间毫秒部分+文件大小+扩展名
myFile.PostedFile.SaveAs(Server.MapPath("photos" + photoName2)); // 保存文件到路径,用Server.MapPath()取当前文件的绝对目录.在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("."); //取得文件名中最后一个"."的索引
string newext = photoName1.Substring(i); //获取文件扩展名
if (newext != ".gif" && newext != ".jpg"&&newext!=".jpeg" && newext != ".bmp" && newext != ".png")
{
Response.Write("文件格式不正确!");
Response.End();
}
DateTime now = DateTime.Now; //获取系统时间
string photoName2 = now.Millisecond.ToString() + "_" + myFile.PostedFile.ContentLength.ToString() + newext; //重新为文件命名,时间毫秒部分+文件大小+扩展名
myFile.PostedFile.SaveAs(Server.MapPath("photos" + photoName2)); // 保存文件到路径,用Server.MapPath()取当前文件的绝对目录.在asp.net里"/"必须用""代替
}
}

HtmlInputFile对象与HTML文件输入元素对应。你可用由id属性指定的名称来访问它。它有下列特性:
* PostedFile:上传文件的内容。
* Accept:以逗号界定的MIME类型列表,指定可能提交的文件类型。
* MaxLength:要提交的文件的最长文件名长度(包括路径)。
* Size:用户输入/选择上传文件的文本框宽度。
以下是HTML输入控制的方法与特性:
* FileName:用户计算机上的完全合格的文件名称。它还包含上传文件的本地路径。
* ContentLength:上传文件的大小(字节)。
* ContentType:上传文件的MIME内容类型。
* InputStream:返回一个指向上传文件的流(Stream)对象,允许你阅读文件内容。
* SaveAs:方便保存上传文件的内容。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: