viper-app/pkg/file_util.go
2023-02-03 16:18:31 +08:00

85 lines
1.2 KiB
Go

package pkg
import (
"errors"
"io"
"mime/multipart"
"os"
"packet-ui/pkg/md5"
"path/filepath"
)
func FileSave(r io.Reader, dst string) (err error) {
var (
fp string
out io.WriteCloser
)
fp, _ = filepath.Split(dst)
err = DirCheck(fp)
out, err = os.Create(dst)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, r)
return
}
// FileMD5 计算文件 md5 值
func FileMD5(file string) (string, error) {
f, err := os.Open(file)
if err != nil {
return "", err
}
info, err := f.Stat()
if err != nil {
return "", err
}
size := info.Size()
return md5.Sum(f, size, BlockSize, ChunkSize)
}
func MultipartMD5(fh *multipart.FileHeader) (string, error) {
f, err := fh.Open()
if err != nil {
return "", err
}
size := fh.Size
return md5.Sum(f, size, BlockSize, ChunkSize)
}
const (
BlockSize = 1 << 10
ChunkSize = BlockSize << 2
)
var (
ErrorIsNotDir = errors.New("path is not dir. ")
)
func DirCheck(dir string) (err error) {
var fi os.FileInfo
if fi, err = os.Stat(dir); err != nil {
if !os.IsExist(err) || os.IsNotExist(err) {
return DirMk(dir)
}
}
if !fi.IsDir() {
err = ErrorIsNotDir
}
return
}
func DirMk(dir string) error {
return os.MkdirAll(dir, 0755)
}