asp.net上传文件代码

首先申明使用命名空间。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
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值