ASP.NET FileUpLoad上图片操作

首先导入IO命名空间

代码如下

protected void Page_Load(object sender, EventArgs e)
    {

    }
   
protected void Button2_Click(object sender, EventArgs e)
    {
       
//Response.Write();
        if (this.fileUpload.PostedFile.FileName == "")
        {
            Response.Write(
"不能上传空文件");
           
return;
        }
       
try
        {
            String path
= Server.MapPath("upload/");//保存上传文件的文件夹upload虚拟路径对应的实际路径
            string pt = path;
           
string fn = "";
           
if (!Directory.Exists(pt)) //如果文件夹不存在则创建
            {
                Directory.CreateDirectory(pt);
            }

               
string filePath = this.fileUpload.PostedFile.FileName;//客户端文件的实际地址
                string serverPath = path + filePath.Substring(filePath.LastIndexOf("\\") + 1);//上传的文件保存在服务器端的路径
                string fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
                System.Text.StringBuilder builder
= new System.Text.StringBuilder(filePath);
                builder.Append(
"<br/>上传文件的类型:" + this.fileUpload.PostedFile.ContentType.ToString() + Environment.NewLine + "");
                builder.Append(
"<br/>客户端文件地址:" + this.fileUpload.PostedFile.FileName + Environment.NewLine + "");
                builder.Append(
"<br/>上传文件的文件名:" + fileName + Environment.NewLine + "");
                builder.Append(
"<br/>上传文件的扩展名:" + filePath.Substring(filePath.LastIndexOf(".") + 1) + Environment.NewLine + "");
                builder.Append(
"<br/>上传文件的大小:" + this.fileUpload.PostedFile.ContentLength / 1024 + "k" + Environment.NewLine + "");
               
if (System.IO.File.Exists(serverPath))//判断服务器上是否有同名文件存在
                {
                   
this.lblState.Text = "这个文件在服务器上已经存在,请不要重复上传!";
                   
return;
                }
               
this.fileUpload.PostedFile.SaveAs(serverPath);//保存文件
                this.lblState.Text = builder.ToString();
        }
       
catch (Exception ex)
        {
            Response.Write(ex.Message);

        }
    }

posted on 2011-08-23 17:01  空白画映  阅读(641)  评论(2编辑  收藏  举报

导航