在设计页面拖进一个input(File)控件,并把它做为服务器控件运行。其ID为myFile;而后拖进一个button,给button的单击时间添加以下代码: 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:方便保存上传文件的内容
|