Asp.net C#上传文件


前台代码:<form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" /><%--上传文件的控件--%>
        <asp:Button ID="Button1" runat="server" OnClick="UploadFiles" Text="提交" /><%--提交上传的文件--%>
    </div>
    </form>
后台代码
protected void UploadFiles(object sender, EventArgs e)
        {         
            try
            {
                if (HttpContext.Current.Request.Files.Count > 0)
                {
                    //System.Web.HttpPostedFile Provides access to individual files that have been uploaded by a client.
                    HttpPostedFile postedFile = HttpContext.Current.Request.Files[0];//获得用户提交的文件

                    string savePath;
                    string dir = HttpContext.Current.Request.PhysicalApplicationPath;//当前应用程序的根目录
                    savePath = dir + "Upload/DocumentFiles/";//保存文件的目录,要事先添加,不会自己添加
                    string date = DateTime.Now.ToString("yyyy-M-d") + "-" + DateTime.Now.Hour.ToString() + "-" +     DateTime.Now.Minute.ToString() + "-" + DateTime.Now.Second.ToString() + "-";//根据自己需要添加
                    savePath +=date+Path.GetFileName(postedFile.FileName);
                    if (File.Exists(savePath))
                    {
                        File.Delete(savePath);//如果文件已经存在就将已存在的文件删除
                    }
                    postedFile.SaveAs(savePath);//将用户提交的文件postedFile保存为savePath                
                  }
            }
            catch (Exception ex)
            {
              
            }     
        }
posted @ 2009-07-21 15:26  leixiaoling  阅读(855)  评论(0编辑  收藏  举报