본문 바로가기
asp.net

[펌] 11. [ASP.NET]파일업로드의 구현

by 사우람 2010. 7. 12.

11. [ASP.NET]파일업로드의 구현

 

 

//중복된 파일을 체크해서 새로운이름으로 생성하는 메서드
private string GetUniqueFileName(string strPath,string fn)
{
 //파일이름,확장자를 잘라내는 로직
 int idxDot=fn.LastIndexOf(".");
 string strName=fn.Substring(0,idxDot);//파일명
 string strExt=fn.Substring(idxDot+1);//확장자..

 //같은이름이 있다고 가정하고 루프를 돌면서 확인..
 bool bExist=true;
 int cnt=0;

 while(bExist)
 {
  if(File.Exists(Path.Combine(strPath,fn)))
  {
   cnt++;
   fn=strName+"("+cnt+")."+strExt;
  }
  else
  {
   bExist=false;
  }//if의 끝      
 }//while의 끝..

 //새롭게 생성된 서버측경로+파일명을 리턴한다. 
 return Path.Combine(strPath,fn);
}

//파일업로드 메서드
private void btnFileUp_Click(object sender, System.EventArgs e)
{
 //파일업로드를 한경우라면..
 if(File1.PostedFile != null)
 {
  try
  {
   //클라이언트의 전체경로를 받는다.
   string wholePath=File1.PostedFile.FileName;
   //파일명만 가져온다.
   string filename=Path.GetFileName(wholePath);
   //서버측 물리적인 경로를 지정한다.
   //string serverLoc=Path.Combine(dirPath,"Data");
   //string serverFileLoc=Path.Combine(serverLoc,filename);
   //만약, 팝폴더 기능처럼..현재 내가 방문하고 있는 폴더위치에 파일을 업로드할 경우는 아래의 코드를 이용한다.
   string serverFileLoc=GetUniqueFileName(strPath,filename);
   //Response.Write(serverFileLoc);
   //실제파일을 업로드합니다.
   File1.PostedFile.SaveAs(serverFileLoc);
   //현재페이지의 하위폴더에 파일이 들어갈것이므로 현재페이지를 새로고침할 필요가 없습니다.
   //만약 현재위치에 파일이 올라가는 경우는 현재페이지를 갱신해야할것이다. 다음과 같다.
   Response.Redirect("WebForm1.aspx?Folder="+virPath);
  }
  catch(Exception ex)
  {
   lblErrorMsg.Text="오류발생 : "+ex.ToString();
  }
 }
 else
 {
  lblErrorMsg.Text="찾아보기를 통하여 업로드할 파일을 선택하세요....";
 }
}
 }