123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- package utils
- import (
- "errors"
- "io/ioutil"
- "log"
- "mime/multipart"
- "net/http"
- "os"
- "path"
- "strings"
- "github.com/shamsher31/goimgext"
- )
- // GetSize 获取文件大小
- func GetSize(f multipart.File) (int, error) {
- content, err := ioutil.ReadAll(f)
- return len(content), err
- }
- // GetExt 获取文件后缀
- func GetExt(fileName string) string {
- return path.Ext(fileName)
- }
- // CheckExist 检查文件是否存在
- func CheckExist(src string) bool {
- _, err := os.Stat(src)
- if err != nil {
- return os.IsNotExist(err)
- }
- return true
- }
- // CheckPermission 检查文件权限
- func CheckPermission(src string) bool {
- _, err := os.Stat(src)
- return os.IsPermission(err)
- }
- // IsNotExistMkDir 检查文件夹是否存在
- // 如果不存在则新建文件夹
- func IsNotExistMkDir(src string) error {
- if exist := !CheckExist(src); exist == false {
- if err := MkDir(src); err != nil {
- return err
- }
- }
- return nil
- }
- // MkDir 新建文件夹
- func MkDir(src string) error {
- err := os.MkdirAll(src, os.ModePerm)
- if err != nil {
- return err
- }
- return nil
- }
- // Open 打开文件
- func Open(name string, flag int, perm os.FileMode) (*os.File, error) {
- f, err := os.OpenFile(name, flag, perm)
- if err != nil {
- return nil, err
- }
- return f, nil
- }
- // GetImgType 获取Img文件类型
- func GetImgType(p string) (string, error) {
- file, err := os.Open(p)
- if err != nil {
- log.Println(err)
- os.Exit(1)
- }
- buff := make([]byte, 512)
- _, err = file.Read(buff)
- if err != nil {
- log.Println(err)
- os.Exit(1)
- }
- filetype := http.DetectContentType(buff)
- ext := imgext.Get()
- for i := 0; i < len(ext); i++ {
- if strings.Contains(ext[i], filetype[6:len(filetype)]) {
- return filetype, nil
- }
- }
- return "", errors.New("Invalid image type")
- }
- // GetType 获取文件类型
- func GetType(p string) (string, error) {
- file, err := os.Open(p)
- if err != nil {
- log.Println(err)
- os.Exit(1)
- }
- buff := make([]byte, 512)
- _, err = file.Read(buff)
- if err != nil {
- log.Println(err)
- }
- filetype := http.DetectContentType(buff)
- //ext := GetExt(p)
- //var list = strings.Split(filetype, "/")
- //filetype = list[0] + "/" + ext
- return filetype, nil
- }
|