分享

大家做C#时上传附件都用什么控件啊?要求可以限制上传文件类型,限制上传文件大小的

 悟静 2012-05-06
用FileUpload控件,上传图片的例子如下:

  首先申明使用命名空间。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:方便保存上传文件的内容。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多