중복되지 않는 파일이름 구하기 > IT 기술백서

IT 기술백서

직접 알아내거나 검색하기 귀찮아서 모아 둔 것

Go lang | 중복되지 않는 파일이름 구하기

본문

업로드 될 디렉토리에 해당 이름이 존재하면 뒤에 "_n" 형식으로 추가해 중복되지 않는 이름을 가져온다.

 

[code]

// GetUniqueFileName 파일이름 유일하게

func GetUniqueFileName(filePath string) string {

  tmpFilePath := filePath

  ext := filepath.Ext(tmpFilePath)

  filePathWithoutExt := strings.TrimSuffix(filePath, ext)


  i := 1

  for true {

    _, err := os.Stat(tmpFilePath)

    if os.IsNotExist(err) {

      break

    }


    tmpFilePath = fmt.Sprintf("%s_%d%s", filePathWithoutExt, i, ext)

    i = i + 1

  }

  return tmpFilePath

}

[/code]

 

사용예)

[code]

...

file, err := c.FormFile("photo")

if err != nil {

  return err

}


dirname := "./upload"

os.MkdirAll(dirname, 0707)

filePath := fmt.Sprintf("%s/%s", dirname, file.Filename)

filePath = g.GetUniqueFileName(filePath)

... 

[/code]

댓글 0개

등록된 댓글이 없습니다.

Menu