FileUpload控件使用初步

FileUpload控件使用初步:

1.实现文件上传

protected void btnSubmit_click(object sender, EventArgs e)

{

if (FileUpload1.HasFile == true)

{

string strErr = "";

//获得上传文件的大小

int filesize = FileUpload1.PostedFile.ContentLength;

if (filesize > 1024 * 1024)

{

        strErr += "文件大小不能大于 1MB\n";

}

if (strErr == "")

{

//获得服务器文件当前路径

string path = Server.MapPath("~");

//把上传文件保存在当前路径的 upload 文件夹中

FileUpload1.PostedFile.SaveAs(path  +  "\\upload\\"  +  FileUpload1.FileName);

lblInfo.Text = "文件保存成功";

}

}

else

{

  lblInfo.Text = "请指定上传的文件";

}

}

 

2. 限定上传的文件的类型

            //取得文件的扩展名,并转换成小写
            string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
            //限定只能上传jpg和gif图片
            string[] allowExtension = { ".jpg", ".gif", ".txt", ".xls" };
            //对上传的文件的类型进行判断
            for (int i = 0; i < allowExtension.Length; i++)
            {
                if (fileExtension == allowExtension[i])
                {
                    fileOk = true;
                    break;
                }
            }

      可以进一步利用FileUpload.PostedFile.ContentType属性进行文件类型判断:
     string fileContentType = FileUpload1.PostedFile.ContentType;
     if (fileContentType =="image/bmp"|| fileContentType =="image/gif"|| fileContentType =="image/pjpeg")
     {

            //-----
      }

3.将上传文件的名称以时间命名

string fileName = Server.MapPath("~") + "\\upload\\" +   DateTime.Now.ToString("yyyyMMddHHmmss")+".jpg";

FileUpload1.SaveAs(fileName);

4.上传大文件

利用ASP.NET控件中的FileUpload控件时,有时候需要上传大容量的文件,可是默认情况下,上传文件的最大容量为4M。如果要实现更大的文件上传,可以在配置文件中改变两个默认设置:httpRuntime下的maxRequestLength和requestLengthDiskThreshold,前者规定了上传的最大容量值,后者设定缓存的大小,以KB为单位。
如:

<configuration>
    <system.web>
       ...
       <httpRuntime maxRequestLength=”10240" requestLengthDiskThreshold=”100" />
       ...
    </system.web>
</configuration>

上面的设置为可以上传不超过10MB的文件,并把缓存阈值改为100KB。

不过要注意,设置太大了会因用户将大量文件传递到该服务器而导致的拒绝服务攻击。

 

posted @ 2012-03-09 21:39  zhouhb  阅读(10341)  评论(0编辑  收藏  举报