Files
open-im-server/pkg/utils/file.go
T

84 lines
1.5 KiB
Go
Raw Normal View History

2021-05-26 19:35:56 +08:00
package utils
2022-03-23 15:44:34 +08:00
import (
"fmt"
2023-03-16 10:46:06 +08:00
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
2022-03-23 15:44:34 +08:00
"math/rand"
"os"
2022-03-23 17:40:51 +08:00
"path"
2022-11-17 11:17:26 +08:00
"strconv"
"strings"
2022-03-23 15:44:34 +08:00
"time"
)
2021-05-26 19:35:56 +08:00
2022-11-17 11:17:26 +08:00
const (
BYTE = 1 << (10 * iota)
KILOBYTE
MEGABYTE
GIGABYTE
TERABYTE
PETABYTE
EXABYTE
)
2021-05-26 19:35:56 +08:00
// Determine whether the given path is a folder
func IsDir(path string) bool {
s, err := os.Stat(path)
if err != nil {
return false
}
return s.IsDir()
}
// Determine whether the given path is a file
func IsFile(path string) bool {
return !IsDir(path)
}
// Create a directory
func MkDir(path string) error {
return os.MkdirAll(path, os.ModePerm)
}
2022-03-23 15:44:34 +08:00
2022-03-23 17:40:51 +08:00
func GetNewFileNameAndContentType(fileName string, fileType int) (string, string) {
suffix := path.Ext(fileName)
newName := fmt.Sprintf("%d-%d%s", time.Now().UnixNano(), rand.Int(), fileName)
2022-03-23 15:44:34 +08:00
contentType := ""
2022-03-23 17:40:51 +08:00
if fileType == constant.ImageType {
contentType = "image/" + suffix[1:]
2022-03-23 15:44:34 +08:00
}
return newName, contentType
}
2022-05-10 10:44:43 +08:00
2022-11-17 11:17:26 +08:00
func ByteSize(bytes uint64) string {
unit := ""
value := float64(bytes)
switch {
case bytes >= EXABYTE:
unit = "E"
value = value / EXABYTE
case bytes >= PETABYTE:
unit = "P"
value = value / PETABYTE
case bytes >= TERABYTE:
unit = "T"
value = value / TERABYTE
case bytes >= GIGABYTE:
unit = "G"
value = value / GIGABYTE
case bytes >= MEGABYTE:
unit = "M"
value = value / MEGABYTE
case bytes >= KILOBYTE:
unit = "K"
value = value / KILOBYTE
case bytes >= BYTE:
unit = "B"
case bytes == 0:
return "0"
2022-05-10 18:28:57 +08:00
}
2022-11-17 11:17:26 +08:00
result := strconv.FormatFloat(value, 'f', 1, 64)
result = strings.TrimSuffix(result, ".0")
return result + unit
2022-05-10 10:44:43 +08:00
}